@mk-co/neox-cli 2.0.48 → 2.0.50

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.
@@ -1,8 +1,8 @@
1
- import*as Me from'fs';import Me__default,{realpathSync,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,createReadStream,readFileSync,existsSync,mkdirSync,writeFileSync}from'fs';import*as te from'path';import te__default,{join,dirname,win32,posix}from'path';import*as In from'os';import In__default,{homedir,platform}from'os';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';import {streamSSE}from'hono/streaming';import Yt,{createHash,createHmac,randomBytes,randomUUID}from'crypto';import {EventEmitter}from'events';import {execa,execaSync}from'execa';import*as ce from'fs/promises';import ce__default,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import aa from'readline';import {fileURLToPath}from'url';import ip from'fast-glob';import {spawn,fork}from'child_process';import Jg from'puppeteer-core';import*as Fu from'net';import xd from'stream';import {StringDecoder}from'string_decoder';import vv from'ajv';import Zv from'axios';import dm from'vm';import Km from'simple-git';import*as Vm from'chokidar';import {EdgeTTS}from'@andresaya/edge-tts';var ng=Object.create;var Vo=Object.defineProperty;var rg=Object.getOwnPropertyDescriptor;var ig=Object.getOwnPropertyNames;var og=Object.getPrototypeOf,ag=Object.prototype.hasOwnProperty;var lg=(a,e)=>()=>(a&&(e=a(a=0)),e);var Uc=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),cg=(a,e)=>{for(var t in e)Vo(a,t,{get:e[t],enumerable:true});},ug=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ig(e))!ag.call(a,n)&&n!==t&&Vo(a,n,{get:()=>e[n],enumerable:!(s=rg(e,n))||s.enumerable});return a};var dg=(a,e,t)=>(t=a!=null?ng(og(a)):{},ug(Vo(t,"default",{value:a,enumerable:true}),a));var qc={};cg(qc,{cliHealthMonitor:()=>fg,cliLogger:()=>m,debugLog:()=>ye,generateCurlCommand:()=>Ft,installCrashHandler:()=>yg,logCurlCommand:()=>Zo});function gg(a,e){let t=new WeakSet;try{return JSON.stringify(a,(s,n)=>{if(e&&s){let r=s.toLowerCase();if(mg.has(r))return "[REDACTED]"}if(typeof n=="bigint")return n.toString();if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};if(typeof n=="function")return "[Function]";if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return n})}catch{return JSON.stringify({error:"[Unserializable payload]"})}}function Ft(a,e,t,s=true){let n=["curl -X POST \\"];n.push(` '${a}' \\`);for(let[i,o]of Object.entries(e)){let l=o;if(s){let c=i.toLowerCase();if(c==="authorization"||c==="x-api-key"||c==="anthropic-api-key")if(l.startsWith("Bearer ")){let u=l.slice(7);l=`Bearer ${u.slice(0,8)}...${u.slice(-4)}`;}else l.length>12&&(l=`${l.slice(0,8)}...${l.slice(-4)}`);}n.push(` -H '${i}: ${l}' \\`);}let r=gg(t,s);return n.push(` -d '${hg(r)}'`),n.join(`
1
+ import*as Me from'fs';import Me__default,{realpathSync,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,createReadStream,readFileSync,existsSync,mkdirSync,writeFileSync}from'fs';import*as te from'path';import te__default,{join,dirname,win32,posix}from'path';import*as In from'os';import In__default,{homedir,platform}from'os';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';import {streamSSE}from'hono/streaming';import Yt,{createHash,createHmac,randomBytes,randomUUID}from'crypto';import {EventEmitter}from'events';import {execa,execaSync}from'execa';import*as ce from'fs/promises';import ce__default,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import aa from'readline';import {fileURLToPath}from'url';import ip from'fast-glob';import {spawn,fork}from'child_process';import Jg from'puppeteer-core';import*as Fu from'net';import xd from'stream';import {StringDecoder}from'string_decoder';import wv from'ajv';import ew from'axios';import dm from'vm';import Km from'simple-git';import*as Vm from'chokidar';import {EdgeTTS}from'@andresaya/edge-tts';var ng=Object.create;var Vo=Object.defineProperty;var rg=Object.getOwnPropertyDescriptor;var ig=Object.getOwnPropertyNames;var og=Object.getPrototypeOf,ag=Object.prototype.hasOwnProperty;var lg=(a,e)=>()=>(a&&(e=a(a=0)),e);var Uc=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),cg=(a,e)=>{for(var t in e)Vo(a,t,{get:e[t],enumerable:true});},ug=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ig(e))!ag.call(a,n)&&n!==t&&Vo(a,n,{get:()=>e[n],enumerable:!(s=rg(e,n))||s.enumerable});return a};var dg=(a,e,t)=>(t=a!=null?ng(og(a)):{},ug(Vo(t,"default",{value:a,enumerable:true}),a));var qc={};cg(qc,{cliHealthMonitor:()=>fg,cliLogger:()=>m,debugLog:()=>ye,generateCurlCommand:()=>Ft,installCrashHandler:()=>yg,logCurlCommand:()=>Zo});function gg(a,e){let t=new WeakSet;try{return JSON.stringify(a,(s,n)=>{if(e&&s){let r=s.toLowerCase();if(mg.has(r))return "[REDACTED]"}if(typeof n=="bigint")return n.toString();if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};if(typeof n=="function")return "[Function]";if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return n})}catch{return JSON.stringify({error:"[Unserializable payload]"})}}function Ft(a,e,t,s=true){let n=["curl -X POST \\"];n.push(` '${a}' \\`);for(let[i,o]of Object.entries(e)){let l=o;if(s){let c=i.toLowerCase();if(c==="authorization"||c==="x-api-key"||c==="anthropic-api-key")if(l.startsWith("Bearer ")){let u=l.slice(7);l=`Bearer ${u.slice(0,8)}...${u.slice(-4)}`;}else l.length>12&&(l=`${l.slice(0,8)}...${l.slice(-4)}`);}n.push(` -H '${i}: ${l}' \\`);}let r=gg(t,s);return n.push(` -d '${hg(r)}'`),n.join(`
2
2
  `)}function hg(a){return a.replace(/'/g,"'\\''")}function Zo(a,e,t){if(process.env.CLI_DEBUG!=="1")return;let s=Ft(a,e,t);m.info("CURL","=== LLM Request CURL Command ==="),m.info("CURL",s),m.info("CURL","=== End CURL Command ==="),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
3
3
  [CURL] === LLM Request CURL Command ===`),console.log(s),console.log(`[CURL] === End CURL Command ===
4
4
  `));}function ye(a,e,t){if(process.env.CLI_DEBUG==="1"&&(m.debug(a,e,t),process.env.CLI_DEBUG_CONSOLE==="1")){let s=a?`[${a}]`:"";t!==void 0?console.log(s,e,t):console.log(s,e);}}function yg(){process.on("uncaughtException",a=>{m.error("CRASH","Uncaught Exception",{name:a.name,message:a.message,stack:a.stack}),setTimeout(()=>process.exit(1),100);}),process.on("unhandledRejection",a=>{m.error("CRASH","Unhandled Rejection",{reason:a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a});});try{process.on("SIGTTIN","ignore"),process.on("SIGTTOU","ignore"),m.info("SIGNAL","TTY control signals (SIGTTIN/SIGTTOU) initialized in crashHandler");}catch{}process.on("exit",()=>{m.close();});}var Xo,m,mg,Qo,fg,W=lg(()=>{Xo=class{logDir;enabled=true;initialized=false;writeStream=null;currentLogFile=null;backpressured=false;constructor(){this.logDir=te__default.join(In__default.homedir(),".neox","logs");}init(){if(!this.initialized)try{Me__default.existsSync(this.logDir)||Me__default.mkdirSync(this.logDir,{recursive:!0}),this.initialized=!0;}catch{this.enabled=false;}}getLogFilePath(){let e=new Date().toISOString().split("T")[0];return te__default.join(this.logDir,`cli-${e}.log`)}ensureStream(){if(!this.enabled||(this.init(),!this.initialized))return null;let e=this.getLogFilePath();return this.currentLogFile!==e&&(this.writeStream&&this.writeStream.end(),this.writeStream=Me__default.createWriteStream(e,{flags:"a"}),this.writeStream.on("error",()=>{this.enabled=false,this.currentLogFile=null;let t=this.writeStream;this.writeStream=null;try{t?.destroy();}catch{}}),this.currentLogFile=e),this.writeStream}formatLocalTime(){let e=new Date,t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),r=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return `${t}-${s}-${n} ${r}:${i}:${o}.${l}`}formatMessage(e,t,s,n){let r=this.formatLocalTime(),i=e.toUpperCase().padEnd(5),o=t?`[${t}]`:"",l=`${r} ${i} ${o} ${s}`;if(n!==void 0)try{let c=this.safeStringify(n);l+=` ${c}`;}catch{l+=" [Serialization Error]";}return l+`
5
- `}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(s,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return s==="parser"||s==="socket"||s==="_httpMessage"||s==="req"||s==="res"?"[Omitted]":n&&n.type==="Buffer"&&Array.isArray(n.data)?"[Buffer]":typeof n=="function"?"[Function]":n instanceof Error?{name:n.name,message:n.message,stack:n.stack}:n})}write(e,t,s,n){if(!this.enabled||this.backpressured&&e==="debug")return;let r=this.formatMessage(e,t,s,n);if(process.env.CLI_DEBUG_CONSOLE==="1")try{process.stderr.write(r);}catch{}let i=this.ensureStream();if(!i)return;!i.write(r)&&!this.backpressured&&(this.backpressured=true,i.once("drain",()=>{this.backpressured=false;}));}debug(e,t,s){this.write("debug",e,t,s);}info(e,t,s){this.write("info",e,t,s);}warn(e,t,s){this.write("warn",e,t,s);}error(e,t,s){this.write("error",e,t,s);}log(e,...t){let s=t.map(n=>{if(typeof n=="string")return n;try{return this.safeStringify(n)}catch{return String(n)}}).join(" ");this.write("info",e,s);}setEnabled(e){this.enabled=e;}getLogDir(){return this.logDir}getCurrentLogFile(){return this.currentLogFile}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null,this.currentLogFile=null);}},m=new Xo,mg=new Set(["api_key","apikey","authorization","token","access_token","refresh_token","password","secret"]);Qo=class{intervalId=null;lastHeartbeat=Date.now();heartbeatCount=0;stdinPausedCount=0;enabled=false;pid=process.pid;start(e=5e3){if(!(this.intervalId||process.env.CLI_DEBUG!=="1")){if(!process.stdin.isTTY){m.debug("HEALTH",`Skipping health monitor in non-TTY process (pid=${this.pid})`);return}this.enabled=true,this.lastHeartbeat=Date.now(),this.heartbeatCount=0,this.stdinPausedCount=0,m.info("HEALTH",`Health monitor started (interval: ${e}ms, pid=${this.pid})`),this.intervalId=setInterval(()=>{this.checkHealth();},e),this.intervalId.unref();}}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.enabled=false,m.info("HEALTH","Health monitor stopped"));}stdinDestroyedCount=0;checkHealth(){let e=Date.now(),t=e-this.lastHeartbeat;this.lastHeartbeat=e,this.heartbeatCount++;let s=this.getStdinState();if(s.isPaused?this.stdinPausedCount++:this.stdinPausedCount=0,s.destroyed){if(this.stdinDestroyedCount++,this.stdinDestroyedCount>=3){m.warn("HEALTH",`[pid=${this.pid}] stdin destroyed for ${this.stdinDestroyedCount} checks, exiting to avoid zombie process`),this.stop(),setTimeout(()=>{process.exit(0);},100);return}}else this.stdinDestroyedCount=0;m.debug("HEALTH",`[pid=${this.pid}] Heartbeat #${this.heartbeatCount}`,{elapsed:`${t}ms`,stdin:s,stdinPausedCount:this.stdinPausedCount}),this.stdinPausedCount>=3&&m.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F stdin has been paused for ${this.stdinPausedCount} consecutive checks!`,{stdin:s}),t>1e4&&m.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F Event loop delay detected: ${t}ms (expected ~5000ms)`);}getStdinState(){let e=process.stdin;return {isPaused:typeof e.isPaused=="function"?e.isPaused():false,isTTY:!!e.isTTY,isRaw:!!e.isRaw,readable:e.readable,destroyed:e.destroyed}}logStdinState(e){if(process.env.CLI_DEBUG!=="1")return;let t=this.getStdinState();m.debug("STDIN",`[${e}] stdin state`,t);}logInkState(e,t){process.env.CLI_DEBUG==="1"&&m.debug("INK",`[${e}]`,t);}},fg=new Qo;});var Vu=Uc((R0,Ku)=>{Ku.exports=Hu;function Hu(a,e,t){a instanceof RegExp&&(a=zu(a,t)),e instanceof RegExp&&(e=zu(e,t));var s=Ju(a,e,t);return s&&{start:s[0],end:s[1],pre:t.slice(0,s[0]),body:t.slice(s[0]+a.length,s[1]),post:t.slice(s[1]+e.length)}}function zu(a,e){var t=e.match(a);return t?t[0]:null}Hu.range=Ju;function Ju(a,e,t){var s,n,r,i,o,l=t.indexOf(a),c=t.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(a===e)return [l,c];for(s=[],r=t.length;u>=0&&!o;)u==l?(s.push(u),l=t.indexOf(a,u+1)):s.length==1?o=[s.pop(),c]:(n=s.pop(),n<r&&(r=n,i=c),c=t.indexOf(e,u+1)),u=l<c&&l>=0?l:c;s.length&&(o=[r,i]);}return o}});var nd=Uc((A0,sd)=>{var Yu=Vu();sd.exports=Pf;var Xu="\0SLASH"+Math.random()+"\0",Qu="\0OPEN"+Math.random()+"\0",ja="\0CLOSE"+Math.random()+"\0",Zu="\0COMMA"+Math.random()+"\0",ed="\0PERIOD"+Math.random()+"\0";function Fa(a){return parseInt(a,10)==a?parseInt(a,10):a.charCodeAt(0)}function If(a){return a.split("\\\\").join(Xu).split("\\{").join(Qu).split("\\}").join(ja).split("\\,").join(Zu).split("\\.").join(ed)}function Mf(a){return a.split(Xu).join("\\").split(Qu).join("{").split(ja).join("}").split(Zu).join(",").split(ed).join(".")}function td(a){if(!a)return [""];var e=[],t=Yu("{","}",a);if(!t)return a.split(",");var s=t.pre,n=t.body,r=t.post,i=s.split(",");i[i.length-1]+="{"+n+"}";var o=td(r);return r.length&&(i[i.length-1]+=o.shift(),i.push.apply(i,o)),e.push.apply(e,i),e}function Pf(a){return a?(a.substr(0,2)==="{}"&&(a="\\{\\}"+a.substr(2)),Bn(If(a),true).map(Mf)):[]}function Df(a){return "{"+a+"}"}function Lf(a){return /^-?0\d/.test(a)}function Of(a,e){return a<=e}function Nf(a,e){return a>=e}function Bn(a,e){var t=[],s=Yu("{","}",a);if(!s)return [a];var n=s.pre,r=s.post.length?Bn(s.post,false):[""];if(/\$$/.test(s.pre))for(var i=0;i<r.length;i++){var o=n+"{"+s.body+"}"+r[i];t.push(o);}else {var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),u=l||c,d=s.body.indexOf(",")>=0;if(!u&&!d)return s.post.match(/,(?!,).*\}/)?(a=s.pre+"{"+s.body+ja+s.post,Bn(a)):[a];var p;if(u)p=s.body.split(/\.\./);else if(p=td(s.body),p.length===1&&(p=Bn(p[0],false).map(Df),p.length===1))return r.map(function(R){return s.pre+p[0]+R});var h;if(u){var g=Fa(p[0]),f=Fa(p[1]),b=Math.max(p[0].length,p[1].length),y=p.length==3?Math.abs(Fa(p[2])):1,w=Of,C=f<g;C&&(y*=-1,w=Nf);var k=p.some(Lf);h=[];for(var T=g;w(T,f);T+=y){var _;if(c)_=String.fromCharCode(T),_==="\\"&&(_="");else if(_=String(T),k){var M=b-_.length;if(M>0){var F=new Array(M+1).join("0");T<0?_="-"+F+_.slice(1):_=F+_;}}h.push(_);}}else {h=[];for(var x=0;x<p.length;x++)h.push.apply(h,Bn(p[x],false));}for(var x=0;x<h.length;x++)for(var i=0;i<r.length;i++){var o=n+h[x]+r[i];(!e||u||o)&&t.push(o);}}return t}});W();var bg=new Set(["127.0.0.1","::1","::ffff:127.0.0.1","localhost"]);function vg(a){return a?bg.has(a):false}var Nr=class{_enabled;_token;_allowLocalWithoutAuth;_publicPaths;constructor(e){this._enabled=!!e,this._token=e?.token??"",this._allowLocalWithoutAuth=e?.allowLocalWithoutAuth??true,this._publicPaths=e?.publicPaths??["/health"];}get enabled(){return this._enabled}get token(){return this._token}enable(e){this._token=e,this._enabled=true;}disable(){this._enabled=false;}updateToken(e){this._token=e;}middleware(){return async(e,t)=>{if(!this._enabled)return t();let s=e.req.path;if(this._publicPaths.some(i=>s===i||s.startsWith(i+"/")))return t();if(this._allowLocalWithoutAuth){let i=e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||e.env?.incoming?.socket?.remoteAddress;if(vg(i))return t()}let n=e.req.header("authorization");if(!n)return e.json({error:"Authorization required"},401);let r=n.split(" ");return r.length!==2||r[0]!=="Bearer"||r[1]!==this._token?e.json({error:"Invalid token"},401):t()}}};function zc(a){let e=a?.maxRequests??120,t=a?.windowMs??6e4,s=new Set(a?.skipPaths??["/health"]),n=new Map,r=setInterval(()=>{let i=Date.now();for(let[o,l]of n)i>l.resetAt&&n.delete(o);},t*2);return r.unref&&r.unref(),async(i,o)=>{if(s.has(i.req.path))return o();let l=i.req.header("x-forwarded-for")?.split(",")[0]?.trim()||i.req.header("x-real-ip")||i.env?.incoming?.socket?.remoteAddress||"unknown",c=Date.now(),u=n.get(l);return (!u||c>u.resetAt)&&(u={count:0,resetAt:c+t},n.set(l,u)),u.count++,i.header("X-RateLimit-Limit",String(e)),i.header("X-RateLimit-Remaining",String(Math.max(0,e-u.count))),i.header("X-RateLimit-Reset",String(Math.ceil(u.resetAt/1e3))),u.count>e?i.json({error:"Too many requests",retryAfter:Math.ceil((u.resetAt-c)/1e3)},429):o()}}var Ns=class{devices=new Map;maxDevices;idleTimeout;cleanupTimer;constructor(e){this.maxDevices=e?.maxDevices??20,this.idleTimeout=e?.idleTimeout??1440*60*1e3,this.cleanupTimer=setInterval(()=>this.cleanup(),6e4),this.cleanupTimer.unref&&this.cleanupTimer.unref();}register(e,t,s){for(let[r,i]of this.devices)if(i.device.name===e.name&&i.ip===s)return i.device=e,i.capabilities=t,i.lastSeen=Date.now(),r;if(this.devices.size>=this.maxDevices){let r=null,i=1/0;for(let[o,l]of this.devices)l.lastSeen<i&&(i=l.lastSeen,r=o);r&&this.devices.delete(r);}let n=Yt.randomUUID();return this.devices.set(n,{id:n,device:e,capabilities:t,registeredAt:Date.now(),lastSeen:Date.now(),ip:s}),n}touch(e){let t=this.devices.get(e);t&&(t.lastSeen=Date.now());}getDevice(e){return this.devices.get(e)??null}removeDevice(e){return this.devices.delete(e)}getAll(){return [...this.devices.values()]}modePrefs=new Map;setPreferredMode(e,t){this.modePrefs.set(e,t);let s=this.devices.get(e);s&&(s.preferredMode=t);}getPreferredMode(e){return this.modePrefs.get(e)??this.devices.get(e)?.preferredMode}cleanup(){let e=Date.now();for(let[t,s]of this.devices)e-s.lastSeen>this.idleTimeout&&this.devices.delete(t);}dispose(){clearInterval(this.cleanupTimer),this.devices.clear();}};function Hc(a){return async(e,t)=>{let s=e.req.header("x-device-id");return s&&(a.touch(s),e.set("deviceId",s)),t()}}W();var $r=class{id="telegram";type="telegram";enabled;token;allowedChatIds;pollingInterval;offset=0;polling=false;timer=null;onMessage;constructor(e,t){this.enabled=e.enabled,this.token=e.botToken,this.allowedChatIds=new Set(e.allowedChatIds??[]),this.pollingInterval=e.pollingInterval??3e3,this.onMessage=t;}async start(){this.polling=true,this.poll(),m.info("TELEGRAM","Polling started");}async stop(){this.polling=false,this.timer&&(clearTimeout(this.timer),this.timer=null),m.info("TELEGRAM","Polling stopped");}async sendMessage(e){let t=`https://api.telegram.org/bot${this.token}/sendMessage`;try{await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:e.chatId,text:e.text,parse_mode:e.format==="markdown"?"MarkdownV2":e.format==="html"?"HTML":void 0})});}catch(s){m.error("TELEGRAM",`sendMessage failed: ${s.message}`);}}async poll(){if(this.polling){try{let e=`https://api.telegram.org/bot${this.token}/getUpdates?offset=${this.offset}&timeout=30`,t=new AbortController,s=setTimeout(()=>t.abort(),35e3),n=await fetch(e,{signal:t.signal});if(clearTimeout(s),n.ok){let r=await n.json();if(r.ok&&Array.isArray(r.result))for(let i of r.result)this.offset=i.update_id+1,await this.handleUpdate(i);}}catch(e){e.name!=="AbortError"&&m.error("TELEGRAM",`Poll error: ${e.message}`);}this.polling&&(this.timer=setTimeout(()=>this.poll(),this.pollingInterval));}}async handleUpdate(e){let t=e.message;if(!t?.text)return;let s=String(t.chat.id);if(this.allowedChatIds.size>0&&!this.allowedChatIds.has(s)){m.warn("TELEGRAM",`Rejected message from unauthorized chat: ${s}`);return}let n={channelId:this.id,chatId:s,text:t.text,from:{id:String(t.from?.id??"unknown"),name:t.from?.first_name??"Unknown"},timestamp:t.date*1e3,raw:e};await this.onMessage(n);}};W();var Fr=class{id="webhook";type="webhook";enabled;secret;onMessage;pendingReplies=new Map;constructor(e,t){this.enabled=e.enabled,this.secret=e.secret,this.onMessage=t;}async start(){m.info("WEBHOOK","Webhook channel ready (passive \u2014 waits for HTTP requests)");}async stop(){this.pendingReplies.clear();}async sendMessage(e){let t=this.pendingReplies.get(e.chatId);t&&(t(e.text),this.pendingReplies.delete(e.chatId));}async handleIncoming(e,t){if(this.secret&&t){let i=createHmac("sha256",this.secret).update(JSON.stringify(e)).digest("hex");if(t!==`sha256=${i}`)throw new Error("Invalid webhook signature")}let s=e.chatId||`wh-${Date.now()}`,n={channelId:this.id,chatId:s,text:e.text||"",from:e.from||{id:"webhook",name:"Webhook"},timestamp:Date.now(),raw:e},r=new Promise(i=>{this.pendingReplies.set(s,i),setTimeout(()=>{this.pendingReplies.has(s)&&(this.pendingReplies.delete(s),i("[timeout] No response within 60s"));},6e4);});return await this.onMessage(n),r}};W();var jr=class{channels=new Map;handler=null;setHandler(e){this.handler=e;}async initialize(e){if(e.telegram?.enabled&&e.telegram.botToken){let t=new $r(e.telegram,s=>this.onMessage(s));this.channels.set(t.id,t);}if(e.webhook?.enabled){let t=new Fr(e.webhook,s=>this.onMessage(s));this.channels.set(t.id,t);}}async startAll(){for(let[e,t]of this.channels)if(t.enabled)try{await t.start(),m.info("CHANNEL",`Started channel: ${e}`);}catch(s){m.error("CHANNEL",`Failed to start ${e}: ${s.message}`);}}async stopAll(){for(let[e,t]of this.channels)try{await t.stop(),m.info("CHANNEL",`Stopped channel: ${e}`);}catch(s){m.error("CHANNEL",`Failed to stop ${e}: ${s.message}`);}}get(e){return this.channels.get(e)}list(){return Array.from(this.channels.values()).map(e=>({id:e.id,type:e.type,enabled:e.enabled}))}async toggle(e,t){let s=this.channels.get(e);return s?(t&&!s.enabled?(s.enabled=true,await s.start()):!t&&s.enabled&&(await s.stop(),s.enabled=false),true):false}async handleWebhook(e,t){let s=this.channels.get(e);return !s||!s.enabled?null:s.type==="webhook"&&"handleIncoming"in s?s.handleIncoming(t):null}async onMessage(e){if(!this.handler){m.warn("CHANNEL","No message handler set, dropping message");return}try{let t=await this.handler(e),s=this.channels.get(e.channelId);s&&await s.sendMessage({chatId:e.chatId,text:t});}catch(t){m.error("CHANNEL",`Handler error: ${t.message}`);}}};function Jc(a,e,t,s){let n=new Hono,r=["http://localhost:*","http://127.0.0.1:*","tauri://localhost",...a.corsOrigins??[]];n.use("*",cors({origin:r,allowMethods:["GET","POST","PATCH","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","X-Device-Id"]}));let i=new Nr(a.auth);n.use("*",i.middleware()),a.rateLimit&&n.use("*",zc(a.rateLimit));let o=s??new Ns;n.use("*",Hc(o)),n.use("*",async(u,d)=>{u.req.path!=="/events"&&u.req.path!=="/status"&&u.req.path!=="/health"&&m.info("SERVER",`${u.req.method} ${u.req.path}`),await d();}),n.get("/events",u=>{let d=u.req.query("sessionId")||void 0;return streamSSE(u,async p=>{let h=t.subscribe(d),g=setInterval(async()=>{try{await p.writeSSE({event:"heartbeat",data:""});}catch{}},3e4);await p.writeSSE({event:"connected",data:JSON.stringify({sessionId:d??"all",timestamp:Date.now()})});try{for await(let f of h)await p.writeSSE({event:f.type,data:JSON.stringify(f)});}catch{}finally{clearInterval(g),h.close();}})}),n.post("/session/:sessionId/chat",async u=>{let{sessionId:d}=u.req.param(),p=await u.req.json();if(!p.mode){let h=u.req.header("x-device-id");if(h){let g=o.getPreferredMode(h);g&&(p.mode=g);}}return e.chat(d,p).catch(h=>{t.publish({sessionId:d,type:"error",data:{type:"error",message:h?.message??String(h),timestamp:Date.now()},timestamp:Date.now()});}),u.json({status:"started",sessionId:d})}),n.post("/session/:sessionId/abort",async u=>{let{sessionId:d}=u.req.param();return e.abort(d),u.json({status:"aborted",sessionId:d})}),n.post("/permission/:requestId/reply",async u=>{let{requestId:d}=u.req.param(),p=await u.req.json();return e.replyPermission(d,p.approved,p.message),u.json({status:"ok"})}),n.get("/mode",u=>u.json({mode:e.getRunMode?.()??"single"})),n.post("/mode",async u=>{let{mode:d}=await u.req.json();return e.setRunMode?.(d),u.json({status:"ok",mode:d})}),n.post("/session/:sessionId/inject",async u=>{let{sessionId:d}=u.req.param(),{message:p}=await u.req.json();return e.injectMessage?.(d,p),u.json({status:"ok"})}),n.post("/session/:sessionId/sandbox",async u=>{let{sessionId:d}=u.req.param(),{enabled:p}=await u.req.json();return e.setSandboxMode?.(d,p),u.json({status:"ok",enabled:p})}),n.post("/session/:sessionId/approval",async u=>{let{sessionId:d}=u.req.param(),{mode:p}=await u.req.json();return e.setApprovalMode?.(d,p),u.json({status:"ok",mode:p})}),n.post("/session/:sessionId/compact",async u=>{let{sessionId:d}=u.req.param();return await e.compactSession?.(d),u.json({status:"ok"})}),n.post("/session/:sessionId/clear",async u=>{let{sessionId:d}=u.req.param();return e.clearSession?.(d),u.json({status:"ok"})}),n.get("/session/:sessionId/context-health",u=>{let{sessionId:d}=u.req.param(),p=e.getContextHealth?.(d);return u.json(p??null)}),n.get("/session/:sessionId/info",async u=>{let{sessionId:d}=u.req.param(),p=await e.getSessionInfo?.(d);return u.json(p??null)}),n.post("/session/:sessionId/compression",async u=>{let{sessionId:d}=u.req.param(),{mode:p}=await u.req.json();return e.setCompressionMode?.(d,p),u.json({status:"ok",mode:p})}),n.get("/session/:sessionId/memory",u=>{let{sessionId:d}=u.req.param(),p=e.getMemoryStats?.(d);return u.json(p??null)}),n.post("/session/:sessionId/memory/clear",u=>{let{sessionId:d}=u.req.param();return e.clearMemory?.(d),u.json({status:"ok"})}),n.post("/session/:sessionId/memory/add",async u=>{let{sessionId:d}=u.req.param(),{role:p,content:h}=await u.req.json();return e.addMemoryMessage?.(d,p,h),u.json({status:"ok"})}),n.get("/tools",u=>{let d=e.getToolList?.();return u.json(d??{count:0,names:[]})}),n.post("/tools/reload",async u=>{let{workDir:d}=await u.req.json();return await e.reloadTools?.(d),u.json({status:"ok"})}),n.post("/workspace",async u=>{let{workDir:d}=await u.req.json();return await e.setWorkspace?.(d),u.json({status:"ok",workDir:d})}),n.post("/checkpoint/start-watching",async u=>{let{sessionId:d}=await u.req.json(),p=await e.startCheckpointWatching?.(d);return u.json({checkpointId:p})}),n.post("/checkpoint/stop-watching",async u=>(await e.stopCheckpointWatching?.(),u.json({status:"ok"}))),n.post("/checkpoint/create",async u=>{let{sessionId:d,label:p}=await u.req.json(),h=await e.createCheckpoint?.(d,p);return u.json(h??null)}),n.post("/checkpoint/rollback",async u=>{let{checkpointId:d}=await u.req.json(),p=await e.rollbackToCheckpoint?.(d);return u.json(p??{success:false})}),n.post("/checkpoint/rollback-file",async u=>{let{filePath:d}=await u.req.json(),p=await e.rollbackSingleFile?.(d);return u.json(p??{success:false})}),n.post("/checkpoint/reapply-file",async u=>{let{filePath:d}=await u.req.json(),p=await e.reapplySingleFile?.(d);return u.json(p??{success:false})}),n.get("/checkpoints",async u=>{let d=u.req.query("limit")?parseInt(u.req.query("limit")):void 0,p=u.req.query("sessionId")||void 0,h=await e.getCheckpoints?.(d,p);return u.json(h??[])}),n.get("/checkpoint/stats",async u=>{let d=await e.getCheckpointStats?.();return u.json(d??{created:0,modified:0,deleted:0,directories:0,total:0})}),n.get("/checkpoint/changes",async u=>{let d=await e.getCheckpointChanges?.();return u.json(d??[])}),n.post("/checkpoint/enabled",async u=>{let{enabled:d}=await u.req.json();return e.setCheckpointEnabled?.(d),u.json({status:"ok",enabled:d})}),n.get("/checkpoint/enabled",u=>{let d=e.isCheckpointEnabled?.()??true;return u.json({enabled:d})}),n.post("/checkpoint/cleanup",async u=>(await e.cleanupCheckpoints?.(),u.json({status:"ok"}))),n.get("/status",u=>u.json({status:"ok",uptime:process.uptime(),pid:process.pid,workDir:a.workDir,activeSessions:e.getActiveSessions(),mode:e.getRunMode?.()??"single"})),n.get("/health",u=>u.text("ok")),n.post("/tts",async u=>{let{enabled:d}=await u.req.json();return e.setTTSEnabled?.(d),u.json({enabled:e.isTTSEnabled?.()??false})}),n.get("/tts",u=>u.json({enabled:e.isTTSEnabled?.()??false,config:e.getTTSConfig?.()??{enabled:false}})),n.post("/device/register",async u=>{let{device:d,capabilities:p}=await u.req.json(),h=u.req.header("x-forwarded-for")?.split(",")[0]?.trim()||u.req.header("x-real-ip")||u.env?.incoming?.socket?.remoteAddress||"unknown",g=o.register(d,p,h);return m.info("SERVER",`Device registered: ${d.type} - ${d.name} (${g})`),u.json({deviceId:g,status:"registered"})}),n.get("/device/:deviceId",u=>{let{deviceId:d}=u.req.param(),p=o.getDevice(d);return p?u.json(p):u.json({error:"Device not found"},404)}),n.get("/devices",u=>{let d=o.getAll();return u.json({count:d.length,devices:d})}),n.delete("/device/:deviceId",u=>{let{deviceId:d}=u.req.param(),p=o.removeDevice(d);return u.json({status:p?"removed":"not_found"})}),n.post("/device/:deviceId/mode",async u=>{let{deviceId:d}=u.req.param(),{mode:p}=await u.req.json();return o.setPreferredMode(d,p),u.json({status:"ok",deviceId:d,mode:p})}),n.get("/device/:deviceId/mode",u=>{let{deviceId:d}=u.req.param(),p=o.getDevice(d);return p?u.json({mode:p.preferredMode??e.getRunMode?.()??"single"}):u.json({error:"Device not found"},404)}),n.get("/host/status",async u=>{let d=await e.getHostStatus?.();return u.json(d??{error:"not available"})}),n.get("/host/agents",async u=>{let d=await e.getHostAgents?.();return u.json(d??[])}),n.get("/host/activity",async u=>{let d=u.req.query("limit")?parseInt(u.req.query("limit")):10,p=await e.getHostActivity?.(d);return u.json(p??[])}),n.get("/host/session",async u=>{let d=await e.getHostSession?.();return u.json(d??null)}),n.get("/host/system",async u=>{let d=await e.getHostSystem?.();return u.json(d??null)}),n.post("/host/interrupt",async u=>{let{reason:d}=await u.req.json().catch(()=>({reason:void 0})),p=await e.hostInterrupt?.(d);return u.json(p??{interrupted:false})}),n.post("/host/command",async u=>{let{text:d,priority:p}=await u.req.json(),h=await e.hostSendCommand?.(d,p);return u.json(h??{queued:false})});let l=async(u,d)=>{let p=u.req.header("x-forwarded-for")?.split(",")[0]?.trim()||u.req.header("x-real-ip")||u.env?.incoming?.socket?.remoteAddress;return !p||!new Set(["127.0.0.1","::1","::ffff:127.0.0.1","localhost"]).has(p)?u.json({error:"Admin endpoints are local-only"},403):d()};n.get("/admin/auth",l,u=>u.json({enabled:i.enabled,hasToken:!!i.token})),n.post("/admin/auth",l,async u=>{let{enabled:d,token:p}=await u.req.json();return p&&i.updateToken(p),d===true&&p?i.enable(p):d===true&&i.token?i.enable(i.token):d===false&&i.disable(),m.info("SERVER",`Auth ${i.enabled?"enabled":"disabled"}`),u.json({enabled:i.enabled})});let c=new jr;return n.get("/channels",u=>u.json(c.list())),n.post("/channels/:id/toggle",async u=>{let{id:d}=u.req.param(),{enabled:p}=await u.req.json(),h=await c.toggle(d,p);return u.json({status:h?"ok":"not_found",id:d,enabled:p})}),n.post("/webhook/:channelId",async u=>{let {channelId:d}=u.req.param();u.req.header("x-hub-signature-256")||u.req.header("x-signature");let h=await u.req.json();try{let g=await c.handleWebhook(d,h);return g===null?u.json({error:"Channel not found or disabled"},404):u.json({reply:g})}catch(g){return u.json({error:g.message},400)}}),{app:n,authGate:i,deviceManager:o,channelRegistry:c}}var Br=class{emitter=new EventEmitter;constructor(){this.emitter.setMaxListeners(100);}publish(e){this.emitter.emit("*",e),this.emitter.emit(`session:${e.sessionId}`,e);}createSink(e="server-bus"){return {name:e,handle:(t,s,n)=>{this.publish({sessionId:t,type:s.type,data:s,tracker:n,timestamp:s.timestamp??Date.now()});}}}subscribe(e){let t=e?`session:${e}`:"*",s=this.emitter,n=false,r=null,i=[],o=u=>{if(r){let d=r;r=null,d({value:u,done:false});}else i.push(u);};s.on(t,o);let l=()=>{if(!n&&(n=true,s.off(t,o),r)){let u=r;r=null,u({value:void 0,done:true});}};return {close:l,[Symbol.asyncIterator](){return {next(){return n?Promise.resolve({value:void 0,done:true}):i.length>0?Promise.resolve({value:i.shift(),done:false}):new Promise(u=>{r=u;})},return(){return l(),Promise.resolve({value:void 0,done:true})}}}}}dispose(){this.emitter.removeAllListeners();}};W();W();W();var hs=null;function Gr(){if(hs!==null)return hs;if(process.platform!=="linux")return hs=false,false;if(process.env.WSL_DISTRO_NAME||process.env.WSLENV||process.env.WSL_INTEROP)return hs=true,true;try{let a=Me__default.readFileSync("/proc/version","utf-8").toLowerCase();if(a.includes("microsoft")||a.includes("wsl"))return hs=!0,!0}catch{}try{if(Me__default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop"))return hs=!0,!0}catch{}return hs=false,false}var Ye=null,fs=null;function Vc(a,e){return {...a,...e,PATH:a.PATH||e.PATH||"",JAVA_HOME:a.JAVA_HOME||e.JAVA_HOME||"",MAVEN_HOME:a.MAVEN_HOME||e.MAVEN_HOME||"",M2_HOME:a.M2_HOME||e.M2_HOME||"",NODE_PATH:a.NODE_PATH||e.NODE_PATH||"",GOPATH:a.GOPATH||e.GOPATH||"",CARGO_HOME:a.CARGO_HOME||e.CARGO_HOME||"",RUSTUP_HOME:a.RUSTUP_HOME||e.RUSTUP_HOME||"",PYENV_ROOT:a.PYENV_ROOT||e.PYENV_ROOT||"",CONDA_PREFIX:a.CONDA_PREFIX||e.CONDA_PREFIX||""}}function Yc(a){let e={};for(let t of a.split(`
5
+ `}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(s,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return s==="parser"||s==="socket"||s==="_httpMessage"||s==="req"||s==="res"?"[Omitted]":n&&n.type==="Buffer"&&Array.isArray(n.data)?"[Buffer]":typeof n=="function"?"[Function]":n instanceof Error?{name:n.name,message:n.message,stack:n.stack}:n})}write(e,t,s,n){if(!this.enabled||this.backpressured&&e==="debug")return;let r=this.formatMessage(e,t,s,n);if(process.env.CLI_DEBUG_CONSOLE==="1")try{process.stderr.write(r);}catch{}let i=this.ensureStream();if(!i)return;!i.write(r)&&!this.backpressured&&(this.backpressured=true,i.once("drain",()=>{this.backpressured=false;}));}debug(e,t,s){this.write("debug",e,t,s);}info(e,t,s){this.write("info",e,t,s);}warn(e,t,s){this.write("warn",e,t,s);}error(e,t,s){this.write("error",e,t,s);}log(e,...t){let s=t.map(n=>{if(typeof n=="string")return n;try{return this.safeStringify(n)}catch{return String(n)}}).join(" ");this.write("info",e,s);}setEnabled(e){this.enabled=e;}getLogDir(){return this.logDir}getCurrentLogFile(){return this.currentLogFile}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null,this.currentLogFile=null);}},m=new Xo,mg=new Set(["api_key","apikey","authorization","token","access_token","refresh_token","password","secret"]);Qo=class{intervalId=null;lastHeartbeat=Date.now();heartbeatCount=0;stdinPausedCount=0;enabled=false;pid=process.pid;start(e=5e3){if(!(this.intervalId||process.env.CLI_DEBUG!=="1")){if(!process.stdin.isTTY){m.debug("HEALTH",`Skipping health monitor in non-TTY process (pid=${this.pid})`);return}this.enabled=true,this.lastHeartbeat=Date.now(),this.heartbeatCount=0,this.stdinPausedCount=0,m.info("HEALTH",`Health monitor started (interval: ${e}ms, pid=${this.pid})`),this.intervalId=setInterval(()=>{this.checkHealth();},e),this.intervalId.unref();}}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.enabled=false,m.info("HEALTH","Health monitor stopped"));}stdinDestroyedCount=0;checkHealth(){let e=Date.now(),t=e-this.lastHeartbeat;this.lastHeartbeat=e,this.heartbeatCount++;let s=this.getStdinState();if(s.isPaused?this.stdinPausedCount++:this.stdinPausedCount=0,s.destroyed){if(this.stdinDestroyedCount++,this.stdinDestroyedCount>=3){m.warn("HEALTH",`[pid=${this.pid}] stdin destroyed for ${this.stdinDestroyedCount} checks, exiting to avoid zombie process`),this.stop(),setTimeout(()=>{process.exit(0);},100);return}}else this.stdinDestroyedCount=0;m.debug("HEALTH",`[pid=${this.pid}] Heartbeat #${this.heartbeatCount}`,{elapsed:`${t}ms`,stdin:s,stdinPausedCount:this.stdinPausedCount}),this.stdinPausedCount>=3&&m.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F stdin has been paused for ${this.stdinPausedCount} consecutive checks!`,{stdin:s}),t>1e4&&m.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F Event loop delay detected: ${t}ms (expected ~5000ms)`);}getStdinState(){let e=process.stdin;return {isPaused:typeof e.isPaused=="function"?e.isPaused():false,isTTY:!!e.isTTY,isRaw:!!e.isRaw,readable:e.readable,destroyed:e.destroyed}}logStdinState(e){if(process.env.CLI_DEBUG!=="1")return;let t=this.getStdinState();m.debug("STDIN",`[${e}] stdin state`,t);}logInkState(e,t){process.env.CLI_DEBUG==="1"&&m.debug("INK",`[${e}]`,t);}},fg=new Qo;});var Vu=Uc((E0,Ku)=>{Ku.exports=Hu;function Hu(a,e,t){a instanceof RegExp&&(a=zu(a,t)),e instanceof RegExp&&(e=zu(e,t));var s=Ju(a,e,t);return s&&{start:s[0],end:s[1],pre:t.slice(0,s[0]),body:t.slice(s[0]+a.length,s[1]),post:t.slice(s[1]+e.length)}}function zu(a,e){var t=e.match(a);return t?t[0]:null}Hu.range=Ju;function Ju(a,e,t){var s,n,r,i,o,l=t.indexOf(a),c=t.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(a===e)return [l,c];for(s=[],r=t.length;u>=0&&!o;)u==l?(s.push(u),l=t.indexOf(a,u+1)):s.length==1?o=[s.pop(),c]:(n=s.pop(),n<r&&(r=n,i=c),c=t.indexOf(e,u+1)),u=l<c&&l>=0?l:c;s.length&&(o=[r,i]);}return o}});var nd=Uc((I0,sd)=>{var Yu=Vu();sd.exports=Df;var Xu="\0SLASH"+Math.random()+"\0",Qu="\0OPEN"+Math.random()+"\0",ja="\0CLOSE"+Math.random()+"\0",Zu="\0COMMA"+Math.random()+"\0",ed="\0PERIOD"+Math.random()+"\0";function Fa(a){return parseInt(a,10)==a?parseInt(a,10):a.charCodeAt(0)}function Mf(a){return a.split("\\\\").join(Xu).split("\\{").join(Qu).split("\\}").join(ja).split("\\,").join(Zu).split("\\.").join(ed)}function Pf(a){return a.split(Xu).join("\\").split(Qu).join("{").split(ja).join("}").split(Zu).join(",").split(ed).join(".")}function td(a){if(!a)return [""];var e=[],t=Yu("{","}",a);if(!t)return a.split(",");var s=t.pre,n=t.body,r=t.post,i=s.split(",");i[i.length-1]+="{"+n+"}";var o=td(r);return r.length&&(i[i.length-1]+=o.shift(),i.push.apply(i,o)),e.push.apply(e,i),e}function Df(a){return a?(a.substr(0,2)==="{}"&&(a="\\{\\}"+a.substr(2)),Bn(Mf(a),true).map(Pf)):[]}function Lf(a){return "{"+a+"}"}function Of(a){return /^-?0\d/.test(a)}function Nf(a,e){return a<=e}function $f(a,e){return a>=e}function Bn(a,e){var t=[],s=Yu("{","}",a);if(!s)return [a];var n=s.pre,r=s.post.length?Bn(s.post,false):[""];if(/\$$/.test(s.pre))for(var i=0;i<r.length;i++){var o=n+"{"+s.body+"}"+r[i];t.push(o);}else {var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),u=l||c,d=s.body.indexOf(",")>=0;if(!u&&!d)return s.post.match(/,(?!,).*\}/)?(a=s.pre+"{"+s.body+ja+s.post,Bn(a)):[a];var p;if(u)p=s.body.split(/\.\./);else if(p=td(s.body),p.length===1&&(p=Bn(p[0],false).map(Lf),p.length===1))return r.map(function(R){return s.pre+p[0]+R});var h;if(u){var g=Fa(p[0]),f=Fa(p[1]),b=Math.max(p[0].length,p[1].length),y=p.length==3?Math.abs(Fa(p[2])):1,w=Nf,C=f<g;C&&(y*=-1,w=$f);var k=p.some(Of);h=[];for(var T=g;w(T,f);T+=y){var _;if(c)_=String.fromCharCode(T),_==="\\"&&(_="");else if(_=String(T),k){var M=b-_.length;if(M>0){var F=new Array(M+1).join("0");T<0?_="-"+F+_.slice(1):_=F+_;}}h.push(_);}}else {h=[];for(var x=0;x<p.length;x++)h.push.apply(h,Bn(p[x],false));}for(var x=0;x<h.length;x++)for(var i=0;i<r.length;i++){var o=n+h[x]+r[i];(!e||u||o)&&t.push(o);}}return t}});W();var bg=new Set(["127.0.0.1","::1","::ffff:127.0.0.1","localhost"]);function vg(a){return a?bg.has(a):false}var Nr=class{_enabled;_token;_allowLocalWithoutAuth;_publicPaths;constructor(e){this._enabled=!!e,this._token=e?.token??"",this._allowLocalWithoutAuth=e?.allowLocalWithoutAuth??true,this._publicPaths=e?.publicPaths??["/health"];}get enabled(){return this._enabled}get token(){return this._token}enable(e){this._token=e,this._enabled=true;}disable(){this._enabled=false;}updateToken(e){this._token=e;}middleware(){return async(e,t)=>{if(!this._enabled)return t();let s=e.req.path;if(this._publicPaths.some(i=>s===i||s.startsWith(i+"/")))return t();if(this._allowLocalWithoutAuth){let i=e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||e.env?.incoming?.socket?.remoteAddress;if(vg(i))return t()}let n=e.req.header("authorization");if(!n)return e.json({error:"Authorization required"},401);let r=n.split(" ");return r.length!==2||r[0]!=="Bearer"||r[1]!==this._token?e.json({error:"Invalid token"},401):t()}}};function zc(a){let e=a?.maxRequests??120,t=a?.windowMs??6e4,s=new Set(a?.skipPaths??["/health"]),n=new Map,r=setInterval(()=>{let i=Date.now();for(let[o,l]of n)i>l.resetAt&&n.delete(o);},t*2);return r.unref&&r.unref(),async(i,o)=>{if(s.has(i.req.path))return o();let l=i.req.header("x-forwarded-for")?.split(",")[0]?.trim()||i.req.header("x-real-ip")||i.env?.incoming?.socket?.remoteAddress||"unknown",c=Date.now(),u=n.get(l);return (!u||c>u.resetAt)&&(u={count:0,resetAt:c+t},n.set(l,u)),u.count++,i.header("X-RateLimit-Limit",String(e)),i.header("X-RateLimit-Remaining",String(Math.max(0,e-u.count))),i.header("X-RateLimit-Reset",String(Math.ceil(u.resetAt/1e3))),u.count>e?i.json({error:"Too many requests",retryAfter:Math.ceil((u.resetAt-c)/1e3)},429):o()}}var Ns=class{devices=new Map;maxDevices;idleTimeout;cleanupTimer;constructor(e){this.maxDevices=e?.maxDevices??20,this.idleTimeout=e?.idleTimeout??1440*60*1e3,this.cleanupTimer=setInterval(()=>this.cleanup(),6e4),this.cleanupTimer.unref&&this.cleanupTimer.unref();}register(e,t,s){for(let[r,i]of this.devices)if(i.device.name===e.name&&i.ip===s)return i.device=e,i.capabilities=t,i.lastSeen=Date.now(),r;if(this.devices.size>=this.maxDevices){let r=null,i=1/0;for(let[o,l]of this.devices)l.lastSeen<i&&(i=l.lastSeen,r=o);r&&this.devices.delete(r);}let n=Yt.randomUUID();return this.devices.set(n,{id:n,device:e,capabilities:t,registeredAt:Date.now(),lastSeen:Date.now(),ip:s}),n}touch(e){let t=this.devices.get(e);t&&(t.lastSeen=Date.now());}getDevice(e){return this.devices.get(e)??null}removeDevice(e){return this.devices.delete(e)}getAll(){return [...this.devices.values()]}modePrefs=new Map;setPreferredMode(e,t){this.modePrefs.set(e,t);let s=this.devices.get(e);s&&(s.preferredMode=t);}getPreferredMode(e){return this.modePrefs.get(e)??this.devices.get(e)?.preferredMode}cleanup(){let e=Date.now();for(let[t,s]of this.devices)e-s.lastSeen>this.idleTimeout&&this.devices.delete(t);}dispose(){clearInterval(this.cleanupTimer),this.devices.clear();}};function Hc(a){return async(e,t)=>{let s=e.req.header("x-device-id");return s&&(a.touch(s),e.set("deviceId",s)),t()}}W();var $r=class{id="telegram";type="telegram";enabled;token;allowedChatIds;pollingInterval;offset=0;polling=false;timer=null;onMessage;constructor(e,t){this.enabled=e.enabled,this.token=e.botToken,this.allowedChatIds=new Set(e.allowedChatIds??[]),this.pollingInterval=e.pollingInterval??3e3,this.onMessage=t;}async start(){this.polling=true,this.poll(),m.info("TELEGRAM","Polling started");}async stop(){this.polling=false,this.timer&&(clearTimeout(this.timer),this.timer=null),m.info("TELEGRAM","Polling stopped");}async sendMessage(e){let t=`https://api.telegram.org/bot${this.token}/sendMessage`;try{await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:e.chatId,text:e.text,parse_mode:e.format==="markdown"?"MarkdownV2":e.format==="html"?"HTML":void 0})});}catch(s){m.error("TELEGRAM",`sendMessage failed: ${s.message}`);}}async poll(){if(this.polling){try{let e=`https://api.telegram.org/bot${this.token}/getUpdates?offset=${this.offset}&timeout=30`,t=new AbortController,s=setTimeout(()=>t.abort(),35e3),n=await fetch(e,{signal:t.signal});if(clearTimeout(s),n.ok){let r=await n.json();if(r.ok&&Array.isArray(r.result))for(let i of r.result)this.offset=i.update_id+1,await this.handleUpdate(i);}}catch(e){e.name!=="AbortError"&&m.error("TELEGRAM",`Poll error: ${e.message}`);}this.polling&&(this.timer=setTimeout(()=>this.poll(),this.pollingInterval));}}async handleUpdate(e){let t=e.message;if(!t?.text)return;let s=String(t.chat.id);if(this.allowedChatIds.size>0&&!this.allowedChatIds.has(s)){m.warn("TELEGRAM",`Rejected message from unauthorized chat: ${s}`);return}let n={channelId:this.id,chatId:s,text:t.text,from:{id:String(t.from?.id??"unknown"),name:t.from?.first_name??"Unknown"},timestamp:t.date*1e3,raw:e};await this.onMessage(n);}};W();var Fr=class{id="webhook";type="webhook";enabled;secret;onMessage;pendingReplies=new Map;constructor(e,t){this.enabled=e.enabled,this.secret=e.secret,this.onMessage=t;}async start(){m.info("WEBHOOK","Webhook channel ready (passive \u2014 waits for HTTP requests)");}async stop(){this.pendingReplies.clear();}async sendMessage(e){let t=this.pendingReplies.get(e.chatId);t&&(t(e.text),this.pendingReplies.delete(e.chatId));}async handleIncoming(e,t){if(this.secret&&t){let i=createHmac("sha256",this.secret).update(JSON.stringify(e)).digest("hex");if(t!==`sha256=${i}`)throw new Error("Invalid webhook signature")}let s=e.chatId||`wh-${Date.now()}`,n={channelId:this.id,chatId:s,text:e.text||"",from:e.from||{id:"webhook",name:"Webhook"},timestamp:Date.now(),raw:e},r=new Promise(i=>{this.pendingReplies.set(s,i),setTimeout(()=>{this.pendingReplies.has(s)&&(this.pendingReplies.delete(s),i("[timeout] No response within 60s"));},6e4);});return await this.onMessage(n),r}};W();var jr=class{channels=new Map;handler=null;setHandler(e){this.handler=e;}async initialize(e){if(e.telegram?.enabled&&e.telegram.botToken){let t=new $r(e.telegram,s=>this.onMessage(s));this.channels.set(t.id,t);}if(e.webhook?.enabled){let t=new Fr(e.webhook,s=>this.onMessage(s));this.channels.set(t.id,t);}}async startAll(){for(let[e,t]of this.channels)if(t.enabled)try{await t.start(),m.info("CHANNEL",`Started channel: ${e}`);}catch(s){m.error("CHANNEL",`Failed to start ${e}: ${s.message}`);}}async stopAll(){for(let[e,t]of this.channels)try{await t.stop(),m.info("CHANNEL",`Stopped channel: ${e}`);}catch(s){m.error("CHANNEL",`Failed to stop ${e}: ${s.message}`);}}get(e){return this.channels.get(e)}list(){return Array.from(this.channels.values()).map(e=>({id:e.id,type:e.type,enabled:e.enabled}))}async toggle(e,t){let s=this.channels.get(e);return s?(t&&!s.enabled?(s.enabled=true,await s.start()):!t&&s.enabled&&(await s.stop(),s.enabled=false),true):false}async handleWebhook(e,t){let s=this.channels.get(e);return !s||!s.enabled?null:s.type==="webhook"&&"handleIncoming"in s?s.handleIncoming(t):null}async onMessage(e){if(!this.handler){m.warn("CHANNEL","No message handler set, dropping message");return}try{let t=await this.handler(e),s=this.channels.get(e.channelId);s&&await s.sendMessage({chatId:e.chatId,text:t});}catch(t){m.error("CHANNEL",`Handler error: ${t.message}`);}}};function Jc(a,e,t,s){let n=new Hono,r=["http://localhost:*","http://127.0.0.1:*","tauri://localhost",...a.corsOrigins??[]];n.use("*",cors({origin:r,allowMethods:["GET","POST","PATCH","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","X-Device-Id"]}));let i=new Nr(a.auth);n.use("*",i.middleware()),a.rateLimit&&n.use("*",zc(a.rateLimit));let o=s??new Ns;n.use("*",Hc(o)),n.use("*",async(u,d)=>{u.req.path!=="/events"&&u.req.path!=="/status"&&u.req.path!=="/health"&&m.info("SERVER",`${u.req.method} ${u.req.path}`),await d();}),n.get("/events",u=>{let d=u.req.query("sessionId")||void 0;return streamSSE(u,async p=>{let h=t.subscribe(d),g=setInterval(async()=>{try{await p.writeSSE({event:"heartbeat",data:""});}catch{}},3e4);await p.writeSSE({event:"connected",data:JSON.stringify({sessionId:d??"all",timestamp:Date.now()})});try{for await(let f of h)await p.writeSSE({event:f.type,data:JSON.stringify(f)});}catch{}finally{clearInterval(g),h.close();}})}),n.post("/session/:sessionId/chat",async u=>{let{sessionId:d}=u.req.param(),p=await u.req.json();if(!p.mode){let h=u.req.header("x-device-id");if(h){let g=o.getPreferredMode(h);g&&(p.mode=g);}}return e.chat(d,p).catch(h=>{t.publish({sessionId:d,type:"error",data:{type:"error",message:h?.message??String(h),timestamp:Date.now()},timestamp:Date.now()});}),u.json({status:"started",sessionId:d})}),n.post("/session/:sessionId/abort",async u=>{let{sessionId:d}=u.req.param();return e.abort(d),u.json({status:"aborted",sessionId:d})}),n.post("/permission/:requestId/reply",async u=>{let{requestId:d}=u.req.param(),p=await u.req.json();return e.replyPermission(d,p.approved,p.message),u.json({status:"ok"})}),n.get("/mode",u=>u.json({mode:e.getRunMode?.()??"single"})),n.post("/mode",async u=>{let{mode:d}=await u.req.json();return e.setRunMode?.(d),u.json({status:"ok",mode:d})}),n.post("/session/:sessionId/inject",async u=>{let{sessionId:d}=u.req.param(),{message:p}=await u.req.json();return e.injectMessage?.(d,p),u.json({status:"ok"})}),n.post("/session/:sessionId/sandbox",async u=>{let{sessionId:d}=u.req.param(),{enabled:p}=await u.req.json();return e.setSandboxMode?.(d,p),u.json({status:"ok",enabled:p})}),n.post("/session/:sessionId/approval",async u=>{let{sessionId:d}=u.req.param(),{mode:p}=await u.req.json();return e.setApprovalMode?.(d,p),u.json({status:"ok",mode:p})}),n.post("/session/:sessionId/compact",async u=>{let{sessionId:d}=u.req.param();return await e.compactSession?.(d),u.json({status:"ok"})}),n.post("/session/:sessionId/clear",async u=>{let{sessionId:d}=u.req.param();return e.clearSession?.(d),u.json({status:"ok"})}),n.get("/session/:sessionId/context-health",u=>{let{sessionId:d}=u.req.param(),p=e.getContextHealth?.(d);return u.json(p??null)}),n.get("/session/:sessionId/info",async u=>{let{sessionId:d}=u.req.param(),p=await e.getSessionInfo?.(d);return u.json(p??null)}),n.post("/session/:sessionId/compression",async u=>{let{sessionId:d}=u.req.param(),{mode:p}=await u.req.json();return e.setCompressionMode?.(d,p),u.json({status:"ok",mode:p})}),n.get("/session/:sessionId/memory",u=>{let{sessionId:d}=u.req.param(),p=e.getMemoryStats?.(d);return u.json(p??null)}),n.post("/session/:sessionId/memory/clear",u=>{let{sessionId:d}=u.req.param();return e.clearMemory?.(d),u.json({status:"ok"})}),n.post("/session/:sessionId/memory/add",async u=>{let{sessionId:d}=u.req.param(),{role:p,content:h}=await u.req.json();return e.addMemoryMessage?.(d,p,h),u.json({status:"ok"})}),n.get("/tools",u=>{let d=e.getToolList?.();return u.json(d??{count:0,names:[]})}),n.post("/tools/reload",async u=>{let{workDir:d}=await u.req.json();return await e.reloadTools?.(d),u.json({status:"ok"})}),n.post("/workspace",async u=>{let{workDir:d}=await u.req.json();return await e.setWorkspace?.(d),u.json({status:"ok",workDir:d})}),n.post("/checkpoint/start-watching",async u=>{let{sessionId:d}=await u.req.json(),p=await e.startCheckpointWatching?.(d);return u.json({checkpointId:p})}),n.post("/checkpoint/stop-watching",async u=>(await e.stopCheckpointWatching?.(),u.json({status:"ok"}))),n.post("/checkpoint/create",async u=>{let{sessionId:d,label:p}=await u.req.json(),h=await e.createCheckpoint?.(d,p);return u.json(h??null)}),n.post("/checkpoint/rollback",async u=>{let{checkpointId:d}=await u.req.json(),p=await e.rollbackToCheckpoint?.(d);return u.json(p??{success:false})}),n.post("/checkpoint/rollback-file",async u=>{let{filePath:d}=await u.req.json(),p=await e.rollbackSingleFile?.(d);return u.json(p??{success:false})}),n.post("/checkpoint/reapply-file",async u=>{let{filePath:d}=await u.req.json(),p=await e.reapplySingleFile?.(d);return u.json(p??{success:false})}),n.get("/checkpoints",async u=>{let d=u.req.query("limit")?parseInt(u.req.query("limit")):void 0,p=u.req.query("sessionId")||void 0,h=await e.getCheckpoints?.(d,p);return u.json(h??[])}),n.get("/checkpoint/stats",async u=>{let d=await e.getCheckpointStats?.();return u.json(d??{created:0,modified:0,deleted:0,directories:0,total:0})}),n.get("/checkpoint/changes",async u=>{let d=await e.getCheckpointChanges?.();return u.json(d??[])}),n.post("/checkpoint/enabled",async u=>{let{enabled:d}=await u.req.json();return e.setCheckpointEnabled?.(d),u.json({status:"ok",enabled:d})}),n.get("/checkpoint/enabled",u=>{let d=e.isCheckpointEnabled?.()??true;return u.json({enabled:d})}),n.post("/checkpoint/cleanup",async u=>(await e.cleanupCheckpoints?.(),u.json({status:"ok"}))),n.get("/status",u=>u.json({status:"ok",uptime:process.uptime(),pid:process.pid,workDir:a.workDir,activeSessions:e.getActiveSessions(),mode:e.getRunMode?.()??"single"})),n.get("/health",u=>u.text("ok")),n.post("/tts",async u=>{let{enabled:d}=await u.req.json();return e.setTTSEnabled?.(d),u.json({enabled:e.isTTSEnabled?.()??false})}),n.get("/tts",u=>u.json({enabled:e.isTTSEnabled?.()??false,config:e.getTTSConfig?.()??{enabled:false}})),n.post("/device/register",async u=>{let{device:d,capabilities:p}=await u.req.json(),h=u.req.header("x-forwarded-for")?.split(",")[0]?.trim()||u.req.header("x-real-ip")||u.env?.incoming?.socket?.remoteAddress||"unknown",g=o.register(d,p,h);return m.info("SERVER",`Device registered: ${d.type} - ${d.name} (${g})`),u.json({deviceId:g,status:"registered"})}),n.get("/device/:deviceId",u=>{let{deviceId:d}=u.req.param(),p=o.getDevice(d);return p?u.json(p):u.json({error:"Device not found"},404)}),n.get("/devices",u=>{let d=o.getAll();return u.json({count:d.length,devices:d})}),n.delete("/device/:deviceId",u=>{let{deviceId:d}=u.req.param(),p=o.removeDevice(d);return u.json({status:p?"removed":"not_found"})}),n.post("/device/:deviceId/mode",async u=>{let{deviceId:d}=u.req.param(),{mode:p}=await u.req.json();return o.setPreferredMode(d,p),u.json({status:"ok",deviceId:d,mode:p})}),n.get("/device/:deviceId/mode",u=>{let{deviceId:d}=u.req.param(),p=o.getDevice(d);return p?u.json({mode:p.preferredMode??e.getRunMode?.()??"single"}):u.json({error:"Device not found"},404)}),n.get("/host/status",async u=>{let d=await e.getHostStatus?.();return u.json(d??{error:"not available"})}),n.get("/host/agents",async u=>{let d=await e.getHostAgents?.();return u.json(d??[])}),n.get("/host/activity",async u=>{let d=u.req.query("limit")?parseInt(u.req.query("limit")):10,p=await e.getHostActivity?.(d);return u.json(p??[])}),n.get("/host/session",async u=>{let d=await e.getHostSession?.();return u.json(d??null)}),n.get("/host/system",async u=>{let d=await e.getHostSystem?.();return u.json(d??null)}),n.post("/host/interrupt",async u=>{let{reason:d}=await u.req.json().catch(()=>({reason:void 0})),p=await e.hostInterrupt?.(d);return u.json(p??{interrupted:false})}),n.post("/host/command",async u=>{let{text:d,priority:p}=await u.req.json(),h=await e.hostSendCommand?.(d,p);return u.json(h??{queued:false})});let l=async(u,d)=>{let p=u.req.header("x-forwarded-for")?.split(",")[0]?.trim()||u.req.header("x-real-ip")||u.env?.incoming?.socket?.remoteAddress;return !p||!new Set(["127.0.0.1","::1","::ffff:127.0.0.1","localhost"]).has(p)?u.json({error:"Admin endpoints are local-only"},403):d()};n.get("/admin/auth",l,u=>u.json({enabled:i.enabled,hasToken:!!i.token})),n.post("/admin/auth",l,async u=>{let{enabled:d,token:p}=await u.req.json();return p&&i.updateToken(p),d===true&&p?i.enable(p):d===true&&i.token?i.enable(i.token):d===false&&i.disable(),m.info("SERVER",`Auth ${i.enabled?"enabled":"disabled"}`),u.json({enabled:i.enabled})});let c=new jr;return n.get("/channels",u=>u.json(c.list())),n.post("/channels/:id/toggle",async u=>{let{id:d}=u.req.param(),{enabled:p}=await u.req.json(),h=await c.toggle(d,p);return u.json({status:h?"ok":"not_found",id:d,enabled:p})}),n.post("/webhook/:channelId",async u=>{let {channelId:d}=u.req.param();u.req.header("x-hub-signature-256")||u.req.header("x-signature");let h=await u.req.json();try{let g=await c.handleWebhook(d,h);return g===null?u.json({error:"Channel not found or disabled"},404):u.json({reply:g})}catch(g){return u.json({error:g.message},400)}}),{app:n,authGate:i,deviceManager:o,channelRegistry:c}}var Br=class{emitter=new EventEmitter;constructor(){this.emitter.setMaxListeners(100);}publish(e){this.emitter.emit("*",e),this.emitter.emit(`session:${e.sessionId}`,e);}createSink(e="server-bus"){return {name:e,handle:(t,s,n)=>{this.publish({sessionId:t,type:s.type,data:s,tracker:n,timestamp:s.timestamp??Date.now()});}}}subscribe(e){let t=e?`session:${e}`:"*",s=this.emitter,n=false,r=null,i=[],o=u=>{if(r){let d=r;r=null,d({value:u,done:false});}else i.push(u);};s.on(t,o);let l=()=>{if(!n&&(n=true,s.off(t,o),r)){let u=r;r=null,u({value:void 0,done:true});}};return {close:l,[Symbol.asyncIterator](){return {next(){return n?Promise.resolve({value:void 0,done:true}):i.length>0?Promise.resolve({value:i.shift(),done:false}):new Promise(u=>{r=u;})},return(){return l(),Promise.resolve({value:void 0,done:true})}}}}}dispose(){this.emitter.removeAllListeners();}};W();W();W();var hs=null;function Gr(){if(hs!==null)return hs;if(process.platform!=="linux")return hs=false,false;if(process.env.WSL_DISTRO_NAME||process.env.WSLENV||process.env.WSL_INTEROP)return hs=true,true;try{let a=Me__default.readFileSync("/proc/version","utf-8").toLowerCase();if(a.includes("microsoft")||a.includes("wsl"))return hs=!0,!0}catch{}try{if(Me__default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop"))return hs=!0,!0}catch{}return hs=false,false}var Ye=null,fs=null;function Vc(a,e){return {...a,...e,PATH:a.PATH||e.PATH||"",JAVA_HOME:a.JAVA_HOME||e.JAVA_HOME||"",MAVEN_HOME:a.MAVEN_HOME||e.MAVEN_HOME||"",M2_HOME:a.M2_HOME||e.M2_HOME||"",NODE_PATH:a.NODE_PATH||e.NODE_PATH||"",GOPATH:a.GOPATH||e.GOPATH||"",CARGO_HOME:a.CARGO_HOME||e.CARGO_HOME||"",RUSTUP_HOME:a.RUSTUP_HOME||e.RUSTUP_HOME||"",PYENV_ROOT:a.PYENV_ROOT||e.PYENV_ROOT||"",CONDA_PREFIX:a.CONDA_PREFIX||e.CONDA_PREFIX||""}}function Yc(a){let e={};for(let t of a.split(`
6
6
  `)){let s=t.indexOf("=");if(s>0){let n=t.substring(0,s),r=t.substring(s+1);e[n]=r;}}return e}async function Xc(a={}){if(Ye)return;if(fs){await fs;return}let e={...process.env};if(process.platform==="win32"){Ye=e;return}let t=Gr(),s=a.maxWaitMs??(t?800:5e3),n=a.background??t,r=async i=>{try{let o=process.env.SHELL||"/bin/zsh";m.debug("SHELL","Preloading shell environment asynchronously...");let l=await execa(o,["-lc","env"],{encoding:"utf8",timeout:i,reject:!1,stdin:"ignore",stdout:"pipe",stderr:"ignore"});if(l.stdout){let c=Yc(l.stdout),u=Vc(c,e);return m.debug("SHELL","Preloaded shell environment successfully",{pathLength:u.PATH?.length}),u}}catch(o){m.warn("SHELL","Failed to preload shell environment",{error:o});}return null};if(n){Ye=e,fs=(async()=>{let i=await r(s);if(i){Ye=i;return}let o=await r(5e3);o&&(Ye=o);})().finally(()=>{fs=null;});return}fs=(async()=>{Ye=await r(s)??e;})().finally(()=>{fs=null;}),await fs;}function Qc(){if(Ye)return Ye;process.env.CLI_DEBUG==="1"&&m.warn("SHELL","\u26A0\uFE0F getShellEnv() cache miss - this should not happen! Call preloadShellEnv() during init.");let a={...process.env};if(process.platform==="win32")return Ye=a,Ye;try{let e=process.env.SHELL||"/bin/zsh",t=execaSync(e,["-ilc","env"],{encoding:"utf8",timeout:5e3,reject:!1});if(t.stdout){let s=Yc(t.stdout);Ye=Vc(s,a),process.env.CLI_DEBUG==="1"&&m.debug("SHELL","Loaded shell environment (sync fallback), PATH length:",{pathLength:Ye.PATH?.length});}else Ye=a;}catch(e){m.warn("SHELL","Failed to load shell environment",{error:e}),Ye=a;}return Ye}W();var ea=class extends EventEmitter{processes=new Map;nextId=1;register(e){let t={pid:e.pid,command:e.command,cwd:e.cwd,startTime:new Date,status:"running",background:e.background,processRef:e.processRef};return this.processes.set(e.pid,t),m.debug("PROCESS_MGR",`Registered process PID=${e.pid}`,{command:e.command.substring(0,50),background:e.background}),this.emit("process:start",t),t}markCompleted(e,t){let s=this.processes.get(e);s&&(s.status=t===0?"completed":"failed",s.exitCode=t,s.endTime=new Date,m.debug("PROCESS_MGR",`Process completed PID=${e}`,{exitCode:t,duration:s.endTime.getTime()-s.startTime.getTime()}),this.emit("process:exit",s),setTimeout(()=>{this.processes.delete(e);},1e3));}unregister(e){this.processes.get(e)&&(this.processes.delete(e),m.debug("PROCESS_MGR",`Unregistered process PID=${e}`));}getRunning(){return Array.from(this.processes.values()).filter(e=>e.status==="running")}getBackgroundRunning(){return Array.from(this.processes.values()).filter(e=>e.status==="running"&&e.background)}getAll(){return Array.from(this.processes.values())}getRecent(e=10){return Array.from(this.processes.values()).sort((t,s)=>s.startTime.getTime()-t.startTime.getTime()).slice(0,e)}get(e){return this.processes.get(e)}isAlive(e){try{return process.kill(e,0),!0}catch{return false}}refreshStatus(){for(let[e,t]of this.processes.entries())t.status==="running"&&(this.isAlive(e)||(t.status="completed",t.endTime=new Date,m.debug("PROCESS_MGR",`Process ${e} is no longer alive, marked as completed`)));}kill(e,t="SIGTERM",s=false){let n=this.processes.get(e);try{return process.kill(e,t),m.info("PROCESS_MGR",`Sent ${t} to process PID=${e}`),s&&setTimeout(()=>{try{this.isAlive(e)&&(process.kill(e,"SIGKILL"),m.info("PROCESS_MGR",`Force killed process PID=${e}`));}catch{}},2e3),n&&(n.status="killed",n.endTime=new Date,this.emit("process:kill",n)),!0}catch(r){return r.code==="ESRCH"?(n&&(n.status="completed",n.endTime=new Date),m.debug("PROCESS_MGR",`Process ${e} not found (already exited)`),false):(m.error("PROCESS_MGR",`Failed to kill process ${e}`,{error:r.message}),false)}}killProcessGroup(e,t="SIGTERM"){try{process.kill(-e,t),m.info("PROCESS_MGR",`Sent ${t} to process group PID=${e}`);let s=this.processes.get(e);return s&&(s.status="killed",s.endTime=new Date,this.emit("process:kill",s)),!0}catch{return this.kill(e,t)}}killAll(e=false){let t=this.getRunning(),s=0,n=0;for(let r of t)(r.background?this.killProcessGroup(r.pid):this.kill(r.pid,"SIGTERM",e))?s++:n++;return m.info("PROCESS_MGR",`Killed ${s} processes, ${n} failed`),{killed:s,failed:n}}cleanup(e=20){let s=this.getAll().filter(r=>r.status!=="running");s.sort((r,i)=>{let o=r.endTime?.getTime()||0;return (i.endTime?.getTime()||0)-o});let n=0;for(let r=e;r<s.length;r++)this.processes.delete(s[r].pid),n++;return n}getStats(){let e=this.getAll();return {total:e.length,running:e.filter(t=>t.status==="running").length,backgroundRunning:e.filter(t=>t.status==="running"&&t.background).length,completed:e.filter(t=>t.status==="completed").length,failed:e.filter(t=>t.status==="failed").length,killed:e.filter(t=>t.status==="killed").length}}formatProcess(e){let t=e.endTime?e.endTime.getTime()-e.startTime.getTime():Date.now()-e.startTime.getTime(),s=this.formatDuration(t),n=this.getStatusIcon(e.status),r=e.background?" [BG]":"",i=e.command.length>40?e.command.substring(0,37)+"...":e.command;return `${n} PID ${e.pid}${r} | ${i} | ${s}`}getStatusIcon(e){switch(e){case "running":return "\u{1F7E2}";case "completed":return "\u2705";case "failed":return "\u274C";case "killed":return "\u{1F6D1}";default:return "\u26AA"}}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`:`${Math.floor(e/36e5)}h ${Math.floor(e%36e5/6e4)}m`}reset(){this.processes.clear(),m.debug("PROCESS_MGR","Process manager reset");}},Zc=new ea;var ta={terminal:true,editor:false,debug:true,trace:true};({...ta});W();function Eg(){let a=process.platform;if(a==="darwin")return te__default.join(In__default.homedir(),"Library","Application Support","Neox");if(a==="win32")return te__default.join(process.env.APPDATA||te__default.join(In__default.homedir(),"AppData","Roaming"),"Neox");{let e=process.env.XDG_CONFIG_HOME||te__default.join(In__default.homedir(),".config");return te__default.join(e,"neox")}}var tu=Eg(),na=te__default.join(tu,"token-usage.json"),eu=3e3,ra=class{stats=null;directoriesReady;saveDebounceTimer=null;constructor(){this.directoriesReady=this.ensureDirectories();}async ensureDirectories(){await ce__default.mkdir(tu,{recursive:true});}async ensureReady(){try{await this.directoriesReady;}catch(e){throw m.error("TokenUsage","Failed to initialize directories",{error:e.message}),e}}generateId(){return `${Date.now()}-${Math.random().toString(36).slice(2,9)}`}async load(){if(await this.ensureReady(),this.stats)return this.stats;try{let e=await ce__default.readFile(na,"utf-8");return this.stats=JSON.parse(e),m.info("TokenUsage","Loaded usage statistics"),this.stats}catch{return m.info("TokenUsage","No existing usage file, creating new"),this.stats={version:"1.0.0",lastUpdated:Date.now(),providers:{},records:[]},this.stats}}async save(){this.saveDebounceTimer&&clearTimeout(this.saveDebounceTimer),this.saveDebounceTimer=setTimeout(async()=>{await this.saveImmediate();},1e3);}async saveImmediate(){if(await this.ensureReady(),!!this.stats)try{this.stats.lastUpdated=Date.now();let e=`${na}.${Date.now()}.tmp`;await ce__default.writeFile(e,JSON.stringify(this.stats,null,2),"utf-8"),await ce__default.rename(e,na),m.info("TokenUsage","Saved usage statistics");}catch(e){m.error("TokenUsage","Failed to save",{error:e.message});}}async recordUsage(e){let t=await this.load(),s={id:this.generateId(),...e};t.records.push(s),t.records.length>eu&&(t.records=t.records.slice(-eu)),t.providers[e.provider]||(t.providers[e.provider]={provider:e.provider,totalRequests:0,successRequests:0,failedRequests:0,totalInputTokens:0,totalOutputTokens:0,totalTokens:0,totalCachedTokens:0,totalOpenaiCachedTokens:0,totalAnthropicCacheReadTokens:0,totalAnthropicCacheCreationTokens:0,totalAnthropicCacheCreation5mTokens:0,totalAnthropicCacheCreation1hTokens:0,avgDuration:0,lastRequestTime:0,models:{}});let n=t.providers[e.provider];n.totalRequests++,e.success?n.successRequests++:n.failedRequests++,n.totalInputTokens+=e.inputTokens,n.totalOutputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.totalCachedTokens+=e.cachedTokens||0,n.totalOpenaiCachedTokens+=e.openaiCachedTokens||0,n.totalAnthropicCacheReadTokens+=e.anthropicCacheReadTokens||0,n.totalAnthropicCacheCreationTokens+=e.anthropicCacheCreationTokens||0,n.totalAnthropicCacheCreation5mTokens+=e.anthropicCacheCreation5mTokens||0,n.totalAnthropicCacheCreation1hTokens+=e.anthropicCacheCreation1hTokens||0,n.lastRequestTime=e.timestamp;let r=n.avgDuration*(n.totalRequests-1)+e.duration;n.avgDuration=Math.round(r/n.totalRequests),n.models[e.model]||(n.models[e.model]={requests:0,inputTokens:0,outputTokens:0,totalTokens:0,cachedTokens:0});let i=n.models[e.model];i.requests++,i.inputTokens+=e.inputTokens,i.outputTokens+=e.outputTokens,i.totalTokens+=e.totalTokens,i.cachedTokens+=e.cachedTokens||0,await this.save();}async getProviderStats(){let e=await this.load();return Object.values(e.providers).sort((t,s)=>s.lastRequestTime-t.lastRequestTime)}async getProviderRecords(e,t=100){return (await this.load()).records.filter(n=>n.provider===e).slice(-t).reverse()}async getRecentRecords(e=50){return (await this.load()).records.slice(-e).reverse()}async getSummary(){let e=await this.load(),t=Object.values(e.providers),s=t.reduce((o,l)=>o+l.totalInputTokens,0),n=t.reduce((o,l)=>o+l.totalCachedTokens,0),r=t.reduce((o,l)=>o+l.totalOpenaiCachedTokens,0),i=t.reduce((o,l)=>o+l.totalAnthropicCacheReadTokens,0);return {totalRequests:t.reduce((o,l)=>o+l.totalRequests,0),totalTokens:t.reduce((o,l)=>o+l.totalTokens,0),totalInputTokens:s,totalOutputTokens:t.reduce((o,l)=>o+l.totalOutputTokens,0),totalCachedTokens:n,totalOpenaiCachedTokens:r,totalAnthropicCacheReadTokens:i,totalAnthropicCacheCreationTokens:t.reduce((o,l)=>o+l.totalAnthropicCacheCreationTokens,0),cacheHitRate:s>0?n/s:0,providerCount:t.length,lastRequestTime:Math.max(...t.map(o=>o.lastRequestTime),0)}}async clearAll(){this.stats={version:"1.0.0",lastUpdated:Date.now(),providers:{},records:[]},await this.saveImmediate(),m.info("TokenUsage","Cleared all usage statistics");}async clearProvider(e){let t=await this.load();delete t.providers[e],t.records=t.records.filter(s=>s.provider!==e),await this.saveImmediate(),m.info("TokenUsage","Cleared usage for provider",{provider:e});}},su=new ra;function Wr(){return {logger:m,shellEnv:{preloadShellEnv:Xc,getShellEnv:Qc},processManager:Zc,capabilities:ta,tokenUsage:su}}W();var qr=class{hosts=new Map;hostConfigs=new Map;workspacePath=null;setWorkspace(e){this.workspacePath=e;for(let t of this.hosts.values())try{t.setWorkDir(e);}catch{}}getWorkspace(){return this.workspacePath}getHost(e){return this.hosts.get(e)}hasHost(e){return this.hosts.has(e)}getHostConfig(e){return this.hostConfigs.get(e)}clearHost(e){this.hosts.delete(e),this.hostConfigs.delete(e);}clearAll(){for(let e of this.hosts.values())try{e.interrupt();}catch{}this.hosts.clear(),this.hostConfigs.clear();}forEachHost(e){for(let[t,s]of this.hosts.entries())e(s,t);}async getOrCreateHost(e){let{sessionId:t,configKey:s,createHost:n}=e,r=this.hosts.get(t);if(r){let o=this.hostConfigs.get(t);if(o===s)return m.info("HOST_CONTROLLER",`\u{1F504} Reusing existing host for session=${t}, configKey=${s}`),r;m.info("HOST_CONTROLLER",`\u{1F5D1}\uFE0F Clearing old host: session=${t}, oldKey=${o}, newKey=${s}`),this.clearHost(t);}m.info("HOST_CONTROLLER",`\u2728 Creating NEW host: session=${t}, configKey=${s}`);let i=await n();return this.hosts.set(t,i),this.hostConfigs.set(t,s),this.workspacePath&&i.setWorkDir(this.workspacePath),i}};function me(a){return a===null?"":typeof a=="string"?a:a.filter(e=>e.type==="text").map(e=>e.text).join("")}var Ig={unknown:0,normal:1,warn:2,soft_limit:3,limit:4};function zr(a){if(!a)return 0;let e=a.trim();return e.length?Math.ceil(e.length/4):0}function Et(a){let e=me(a.content),t=zr(e),s=a.tool_calls?.length?zr(JSON.stringify(a.tool_calls)):0;return t+s}function tt(a){return a.reduce((e,t)=>e+Et(t),0)}function Fs(a){let e={systemTokens:0,userTokens:0,assistantTokens:0,toolCallTokens:0,toolResultTokens:0,totalTokens:0};for(let t of a){let s=me(t.content),n=zr(s),r=t.tool_calls?.length?zr(JSON.stringify(t.tool_calls)):0;switch(t.role){case "system":e.systemTokens+=n;break;case "user":e.userTokens+=n;break;case "assistant":e.assistantTokens+=n,e.toolCallTokens+=r;break;case "tool":e.toolResultTokens+=n;break;default:e.userTokens+=n+r;}}return e.totalTokens=e.systemTokens+e.userTokens+e.assistantTokens+e.toolCallTokens+e.toolResultTokens,e}function Mg(a,e,t){return !a.contextWindow&&!a.autoCompactLimit?"unknown":a.autoCompactLimit&&e>=a.autoCompactLimit?"limit":t===void 0||a.contextWindow===void 0?"unknown":t>=a.warnThresholds.hard?"limit":t>=a.warnThresholds.soft?"soft_limit":t>=a.warnThresholds.warn?"warn":"normal"}var Hr=class{profile;promptTokensActual=0;completionTokensActual=0;promptTokensEstimate=0;completionTokensEstimate=0;constructor(e){this.profile=e;}updateProfile(e){this.profile=e,this.reset();}reset(){this.promptTokensActual=0,this.completionTokensActual=0,this.promptTokensEstimate=0,this.completionTokensEstimate=0;}setPromptEstimateFromMessages(e){return this.promptTokensActual>0?(this.completionTokensEstimate=0,this.getSnapshot()):(this.promptTokensEstimate=tt(e),this.promptTokensActual=0,this.completionTokensActual=0,this.completionTokensEstimate=0,this.getSnapshot())}addEstimatedOutputTokens(e){return this.completionTokensEstimate=Math.max(0,this.completionTokensEstimate+e),this.getSnapshot()}recordActualUsage(e,t,s){return this.promptTokensActual=e,this.completionTokensActual=t,this.promptTokensEstimate=0,this.completionTokensEstimate=0,this.getSnapshot(s)}getSnapshot(e){let t=this.promptTokensActual||this.promptTokensEstimate,s=this.completionTokensActual+this.completionTokensEstimate,n=t+s,r=this.profile.contextWindow?n/this.profile.contextWindow:void 0,i=Mg(this.profile,n,r);return {profile:this.profile,tokensUsed:n,promptTokens:t,completionTokens:s,messageCount:e,pressure:r,state:i,timestamp:Date.now()}}getStateRank(e){return Ig[e]}estimateMessagesForDisplay(e){return tt(e)}recordCalibration(e,t,s){if(process.env.CLI_DEBUG){let n=t+s,r=e>0?n/e:0;console.log(`[MemoryPressure] \u6821\u51C6: \u4F30\u7B97=${e}, \u5B9E\u9645=${n}, \u6BD4\u7387=${r.toFixed(3)}`);}}};function js(){let a=new Date,e=a.toISOString().slice(0,10).replace(/-/g,""),t=a.toISOString().slice(11,19).replace(/:/g,""),s=Math.random().toString(36).slice(2,6);return `session_${e}_${t}_${s}`}var ys=class a{sessionId;filePath;directory;options;sequenceNumber=0;initialized=false;constructor(e){typeof e=="string"&&(e={sessionId:e}),this.sessionId=e.sessionId,this.options=e,this.directory=e.directory||te__default.join(In__default.homedir(),".neox","sessions"),this.filePath=te__default.join(this.directory,`${this.sessionId}.jsonl`);}async ensureDirectory(){await ce__default.mkdir(this.directory,{recursive:true});}async ensureInitialized(){if(!this.initialized){await this.ensureDirectory();try{await ce__default.access(this.filePath);let e=await this.readAllItems();e.length>0&&(this.sequenceNumber=Math.max(...e.map(t=>t.seq))+1);}catch{if(this.options.autoCreateMeta!==false){let e={sessionId:this.sessionId,createdAt:new Date().toISOString(),agentName:this.options.agentName,model:this.options.model};await this.appendItem({type:"meta",data:e});}}this.initialized=true;}}async readAllItems(){let e=[];try{let t=Me__default.createReadStream(this.filePath,{encoding:"utf-8"}),s=aa.createInterface({input:t,crlfDelay:1/0});for await(let n of s)if(n.trim())try{let r=JSON.parse(n);e.push(r);}catch{console.warn(`Invalid JSONL line: ${n.slice(0,50)}...`);}}catch(t){if(t.code!=="ENOENT")throw t}return e.sort((t,s)=>t.seq-s.seq),e}async appendItem(e){await this.ensureDirectory();let t={item:e,timestamp:Date.now(),seq:this.sequenceNumber++},s=JSON.stringify(t)+`
7
7
  `;await ce__default.appendFile(this.filePath,s,"utf-8");}async writeAllItems(e){await this.ensureDirectory();let t=e.map(s=>JSON.stringify(s)).join(`
8
8
  `);await ce__default.writeFile(this.filePath,t?t+`
@@ -450,13 +450,13 @@ URL: ${a}`}}};W();function $u(a){return {...Vr,async function(e){try{m.debug("BR
450
450
  Please download it from https://github.com/microsoft/java-debug/releases`)}let e=this.getJavaCommand();return new Promise((t,s)=>{let n=this.config.startupTimeout||1e4,r="",i=setTimeout(()=>{this.isRunning||(this.stop(),s(new Error(`Java Debug Server startup timeout (${n}ms)
451
451
  Output so far:
452
452
  ${r}`)));},n);this.process=spawn(e,["-jar",this.config.jarPath],{stdio:["pipe","pipe","pipe"]}),this.process.stdout?.on("data",o=>{let l=o.toString();r+=l,this.emit("stdout",l);let c=l.match(/Listening.*?address:\s*(\d+)/i);c&&(this.port=parseInt(c[1],10),this.isRunning=true,clearTimeout(i),this.emit("started",this.port),t(this.port));let u=l.match(/listening.*?port\s*(\d+)/i);u&&(this.port=parseInt(u[1],10),this.isRunning=true,clearTimeout(i),this.emit("started",this.port),t(this.port));}),this.process.stderr?.on("data",o=>{let l=o.toString();r+=l,this.emit("stderr",l),l.toLowerCase().includes("error")&&this.emit("error",new Error(l));}),this.process.on("exit",(o,l)=>{this.isRunning=false,this.emit("exit",{code:o,signal:l}),o!==0&&o!==null&&s(new Error(`Java Debug Server exited with code ${o}
453
- ${r}`));}),this.process.on("error",o=>{clearTimeout(i),this.isRunning=false,this.emit("error",o),s(o);});})}stop(){this.process&&(this.process.kill(),this.process=null),this.isRunning=false,this.port=0,this.emit("stopped");}getPort(){return this.port}isServerRunning(){return this.isRunning}getJavaCommand(){return this.config.javaHome?te.join(this.config.javaHome,"bin","java"):process.env.JAVA_HOME?te.join(process.env.JAVA_HOME,"bin","java"):"java"}async initialize(){if(!this.process||!this.isRunning)throw new Error("Server is not running");let e={jsonrpc:"2.0",id:1,method:"initialize",params:{processId:process.pid,capabilities:{}}};this.sendLSPMessage(e);let t={jsonrpc:"2.0",method:"initialized",params:{}};this.sendLSPMessage(t);}sendLSPMessage(e){if(!this.process?.stdin)throw new Error("Server stdin is not available");let t=JSON.stringify(e),r=`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
453
+ ${r}`));}),this.process.on("error",o=>{clearTimeout(i),this.isRunning=false,this.emit("error",o),s(o);});})}stop(){this.process&&(this.process.kill(),this.process=null),this.isRunning=false,this.port=0,this.emit("stopped");}getPort(){return this.port}isServerRunning(){return this.isRunning}getJavaCommand(){let e=process.platform==="win32"?".exe":"";return this.config.javaHome?te.join(this.config.javaHome,"bin",`java${e}`):process.env.JAVA_HOME?te.join(process.env.JAVA_HOME,"bin",`java${e}`):"java"}async initialize(){if(!this.process||!this.isRunning)throw new Error("Server is not running");let e={jsonrpc:"2.0",id:1,method:"initialize",params:{processId:process.pid,capabilities:{}}};this.sendLSPMessage(e);let t={jsonrpc:"2.0",method:"initialized",params:{}};this.sendLSPMessage(t);}sendLSPMessage(e){if(!this.process?.stdin)throw new Error("Server stdin is not available");let t=JSON.stringify(e),r=`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
454
454
  \r
455
- `+t;this.process.stdin.write(r);}async startDAPServer(){return new Promise((e,t)=>{let s=setTimeout(()=>{t(new Error("Timeout waiting for DAP server to start"));},5e3),n=i=>{let o=i.match(/DAP.*?port\s*(\d+)/i);if(o){let l=parseInt(o[1],10);clearTimeout(s),this.removeListener("stdout",n),e(l);}};this.on("stdout",n);let r={jsonrpc:"2.0",id:2,method:"vscode.java.startDebugSession",params:{}};this.sendLSPMessage(r);})}};var ci=class extends EventEmitter{sessions=new Map;config;sessionIdCounter=0;constructor(e){super(),this.config=e,this.config.sessionTimeout&&setInterval(()=>{this.cleanupInactiveSessions();},6e4);}async launch(e){let t=this.generateSessionId();try{let s=new li({jarPath:this.config.javaDebugJarPath,javaHome:this.config.javaHome,startupTimeout:this.config.defaultTimeout}),n=await s.start(),r=new Nn;await r.connect("localhost",n),await r.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await r.launch({mainClass:e.mainClass,projectName:e.projectPath.split("/").pop(),classPaths:e.classpath?[e.classpath]:[],args:e.args?.join(" "),vmArgs:e.vmArgs?.join(" "),cwd:e.cwd||e.projectPath,stopOnEntry:e.stopOnEntry}),await r.configurationDone();let i={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:i,client:r,server:s}),this.setupClientListeners(t,r),{sessionId:t,status:"running",message:`Debug session started for ${e.mainClass}`}}catch(s){throw new Error(`Failed to launch debug session: ${s.message}`)}}async attach(e){let t=this.generateSessionId();try{let s=new Nn;await s.connect(e.hostName||"localhost",e.port),await s.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await s.attach({hostName:e.hostName||"localhost",port:e.port,timeout:e.timeout||5e3}),await s.configurationDone();let n={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:n,client:s,server:null}),this.setupClientListeners(t,s),{sessionId:t,status:"running",message:`Attached to Java process on ${e.hostName||"localhost"}:${e.port}`}}catch(s){throw new Error(`Failed to attach to process: ${s.message}`)}}async setBreakpoint(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=(await t.client.setBreakpoints({source:{path:e.filePath},breakpoints:[{line:e.line,condition:e.condition,hitCondition:e.hitCondition,logMessage:e.logMessage}]})).body.breakpoints[0];return t.session.breakpoints.has(e.filePath)||t.session.breakpoints.set(e.filePath,[]),t.session.breakpoints.get(e.filePath).push(n),{breakpointId:n.id||-1,verified:n.verified,line:n.line||e.line,message:n.verified?`Breakpoint set at line ${n.line}`:`Breakpoint not verified: ${n.message||"Unknown reason"}`}}catch(s){throw new Error(`Failed to set breakpoint: ${s.message}`)}}async continue(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1;return await t.client.continue({threadId:s}),t.session.status="running",await this.waitForStoppedOrTimeout(t,s)}catch(s){throw new Error(`Failed to continue execution: ${s.message}`)}}async stepOver(e){return await this.performStep(e,"stepOver")}async stepInto(e){return await this.performStep(e,"stepInto")}async stepOut(e){return await this.performStep(e,"stepOut")}async getVariables(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=t.session.currentThreadId||1,n=e.frameId||t.session.currentFrameId||0,r=await t.client.stackTrace({threadId:s,startFrame:0,levels:1});if(r.body.stackFrames.length===0)throw new Error("No stack frames available");let i=r.body.stackFrames[0],o=await t.client.scopes({frameId:i.id}),l=[];for(let c of o.body.scopes){if(e.filter==="local"&&c.name!=="Local"||e.filter==="arguments"&&c.name!=="Arguments")continue;let u=await t.client.variables({variablesReference:c.variablesReference});l.push(...u.body.variables);}return {variables:l.map(c=>({name:c.name,value:c.value,type:c.type||"unknown",variablesReference:c.variablesReference})),message:`Retrieved ${l.length} variables`}}catch(s){throw new Error(`Failed to get variables: ${s.message}`)}}async getStackTrace(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1,n=await t.client.stackTrace({threadId:s,startFrame:0,levels:50});return {stackFrames:n.body.stackFrames.map(r=>({id:r.id,name:r.name,source:{path:r.source?.path||"unknown",line:r.line},presentationHint:r.presentationHint})),totalFrames:n.body.totalFrames||n.body.stackFrames.length,message:`Retrieved ${n.body.stackFrames.length} stack frames`}}catch(s){throw new Error(`Failed to get stack trace: ${s.message}`)}}async evaluate(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.frameId||t.session.currentFrameId,n=await t.client.evaluate({expression:e.expression,frameId:s,context:e.context||"repl"});return {result:n.body.result,type:n.body.type||"unknown",variablesReference:n.body.variablesReference,message:`Expression evaluated: ${n.body.result}`}}catch(s){throw new Error(`Failed to evaluate expression: ${s.message}`)}}async stop(e){let t=this.getSessionContext(e.sessionId);try{return await t.client.disconnectRequest({terminateDebuggee:e.terminateDebuggee!==!1}),t.server&&t.server.stop(),this.sessions.delete(e.sessionId),{status:"terminated",message:"Debug session stopped"}}catch(s){return this.sessions.delete(e.sessionId),{status:"terminated",message:`Debug session stopped (with error: ${s.message})`}}}getSession(e){return this.sessions.get(e)?.session||null}listSessions(){return Array.from(this.sessions.values()).map(e=>e.session)}generateSessionId(){return `java-debug-${Date.now()}-${++this.sessionIdCounter}`}getSessionContext(e){let t=this.sessions.get(e);if(!t)throw new Error(`Debug session not found: ${e}`);return t}setupClientListeners(e,t){t.on("event",s=>{let n=this.sessions.get(e);if(n){switch(s.event){case "stopped":n.session.status="stopped",n.session.currentThreadId=s.body.threadId,n.session.stoppedReason=s.body.reason,n.session.lastActivity=Date.now();break;case "continued":n.session.status="running",n.session.lastActivity=Date.now();break;case "terminated":n.session.status="terminated",n.session.lastActivity=Date.now();break}this.emit("session:event",{sessionId:e,event:s.event,body:s.body});}});}async waitForStoppedOrTimeout(e,t,s=5e3){return new Promise(n=>{let r=setTimeout(()=>{e.client.off("event:stopped",i),e.client.off("event:terminated",i),n({status:"running",message:"Program is running"});},s),i=o=>{clearTimeout(r),e.client.off("event:stopped",i),e.client.off("event:terminated",i),o.reason?n({status:"stopped",stoppedReason:o.reason,location:o.source?{filePath:o.source.path,line:o.line,column:o.column||0}:void 0,message:`Program stopped: ${o.reason}`}):n({status:"terminated",message:"Program terminated"});};e.client.once("event:stopped",i),e.client.once("event:terminated",i);})}async performStep(e,t){let s=this.getSessionContext(e.sessionId);s.session.lastActivity=Date.now();try{let n=e.threadId||s.session.currentThreadId||1;switch(t){case "stepOver":await s.client.next({threadId:n});break;case "stepInto":await s.client.stepIn({threadId:n});break;case "stepOut":await s.client.stepOut({threadId:n});break}return new Promise((r,i)=>{let o=setTimeout(()=>{i(new Error("Step operation timeout"));},5e3);s.client.once("event:stopped",async l=>{clearTimeout(o);try{let u=(await s.client.stackTrace({threadId:n,startFrame:0,levels:1})).body.stackFrames[0];s.session.currentFrameId=u.id,r({status:"stopped",location:{filePath:u.source?.path||"unknown",line:u.line,method:u.name},message:`Stepped to ${u.name} at line ${u.line}`});}catch(c){i(c);}});})}catch(n){throw new Error(`Failed to perform step: ${n.message}`)}}cleanupInactiveSessions(){if(!this.config.sessionTimeout)return;let e=Date.now();for(let[t,s]of this.sessions.entries())e-s.session.lastActivity>this.config.sessionTimeout&&(console.log(`Cleaning up inactive session: ${t}`),this.stop({sessionId:t}).catch(r=>{console.error(`Failed to stop inactive session ${t}:`,r);}));}};var gf=fileURLToPath(import.meta.url),hf=te.dirname(gf);async function ff(){let a=process,e=[...a.resourcesPath?[te.join(a.resourcesPath,"java-debug","com.microsoft.java.debug.plugin.jar")]:[],te.join(process.cwd(),"resources","java-debug","com.microsoft.java.debug.plugin.jar"),te.join(hf,"..","..","..","resources","java-debug","com.microsoft.java.debug.plugin.jar")];for(let t of e)try{return await ce.access(t),console.log(`\u2713 \u627E\u5230\u5185\u7F6E Java Debug JAR: ${t}`),t}catch{}return null}async function Bu(a){if(a)try{return await ce.access(a),console.log(`\u2713 \u4F7F\u7528\u914D\u7F6E\u7684 Java Debug JAR: ${a}`),a}catch{console.warn(`\u26A0\uFE0F \u914D\u7F6E\u7684 JAR \u8DEF\u5F84\u65E0\u6548: ${a}`);}let e=await ff();if(e)return e;throw new Error(`Java Debug JAR \u672A\u627E\u5230\uFF01
455
+ `+t;this.process.stdin.write(r);}async startDAPServer(){return new Promise((e,t)=>{let s=setTimeout(()=>{t(new Error("Timeout waiting for DAP server to start"));},5e3),n=i=>{let o=i.match(/DAP.*?port\s*(\d+)/i);if(o){let l=parseInt(o[1],10);clearTimeout(s),this.removeListener("stdout",n),e(l);}};this.on("stdout",n);let r={jsonrpc:"2.0",id:2,method:"vscode.java.startDebugSession",params:{}};this.sendLSPMessage(r);})}};var ci=class extends EventEmitter{sessions=new Map;config;sessionIdCounter=0;constructor(e){super(),this.config=e,this.config.sessionTimeout&&setInterval(()=>{this.cleanupInactiveSessions();},6e4);}async launch(e){let t=this.generateSessionId();try{let s=new li({jarPath:this.config.javaDebugJarPath,javaHome:this.config.javaHome,startupTimeout:this.config.defaultTimeout}),n=await s.start(),r=new Nn;await r.connect("localhost",n),await r.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await r.launch({mainClass:e.mainClass,projectName:te__default.basename(e.projectPath),classPaths:e.classpath?[e.classpath]:[],args:e.args?.join(" "),vmArgs:e.vmArgs?.join(" "),cwd:e.cwd||e.projectPath,stopOnEntry:e.stopOnEntry}),await r.configurationDone();let i={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:i,client:r,server:s}),this.setupClientListeners(t,r),{sessionId:t,status:"running",message:`Debug session started for ${e.mainClass}`}}catch(s){throw new Error(`Failed to launch debug session: ${s.message}`)}}async attach(e){let t=this.generateSessionId();try{let s=new Nn;await s.connect(e.hostName||"localhost",e.port),await s.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await s.attach({hostName:e.hostName||"localhost",port:e.port,timeout:e.timeout||5e3}),await s.configurationDone();let n={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:n,client:s,server:null}),this.setupClientListeners(t,s),{sessionId:t,status:"running",message:`Attached to Java process on ${e.hostName||"localhost"}:${e.port}`}}catch(s){throw new Error(`Failed to attach to process: ${s.message}`)}}async setBreakpoint(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=(await t.client.setBreakpoints({source:{path:e.filePath},breakpoints:[{line:e.line,condition:e.condition,hitCondition:e.hitCondition,logMessage:e.logMessage}]})).body.breakpoints[0];return t.session.breakpoints.has(e.filePath)||t.session.breakpoints.set(e.filePath,[]),t.session.breakpoints.get(e.filePath).push(n),{breakpointId:n.id||-1,verified:n.verified,line:n.line||e.line,message:n.verified?`Breakpoint set at line ${n.line}`:`Breakpoint not verified: ${n.message||"Unknown reason"}`}}catch(s){throw new Error(`Failed to set breakpoint: ${s.message}`)}}async continue(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1;return await t.client.continue({threadId:s}),t.session.status="running",await this.waitForStoppedOrTimeout(t,s)}catch(s){throw new Error(`Failed to continue execution: ${s.message}`)}}async stepOver(e){return await this.performStep(e,"stepOver")}async stepInto(e){return await this.performStep(e,"stepInto")}async stepOut(e){return await this.performStep(e,"stepOut")}async getVariables(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=t.session.currentThreadId||1,n=e.frameId||t.session.currentFrameId||0,r=await t.client.stackTrace({threadId:s,startFrame:0,levels:1});if(r.body.stackFrames.length===0)throw new Error("No stack frames available");let i=r.body.stackFrames[0],o=await t.client.scopes({frameId:i.id}),l=[];for(let c of o.body.scopes){if(e.filter==="local"&&c.name!=="Local"||e.filter==="arguments"&&c.name!=="Arguments")continue;let u=await t.client.variables({variablesReference:c.variablesReference});l.push(...u.body.variables);}return {variables:l.map(c=>({name:c.name,value:c.value,type:c.type||"unknown",variablesReference:c.variablesReference})),message:`Retrieved ${l.length} variables`}}catch(s){throw new Error(`Failed to get variables: ${s.message}`)}}async getStackTrace(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1,n=await t.client.stackTrace({threadId:s,startFrame:0,levels:50});return {stackFrames:n.body.stackFrames.map(r=>({id:r.id,name:r.name,source:{path:r.source?.path||"unknown",line:r.line},presentationHint:r.presentationHint})),totalFrames:n.body.totalFrames||n.body.stackFrames.length,message:`Retrieved ${n.body.stackFrames.length} stack frames`}}catch(s){throw new Error(`Failed to get stack trace: ${s.message}`)}}async evaluate(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.frameId||t.session.currentFrameId,n=await t.client.evaluate({expression:e.expression,frameId:s,context:e.context||"repl"});return {result:n.body.result,type:n.body.type||"unknown",variablesReference:n.body.variablesReference,message:`Expression evaluated: ${n.body.result}`}}catch(s){throw new Error(`Failed to evaluate expression: ${s.message}`)}}async stop(e){let t=this.getSessionContext(e.sessionId);try{return await t.client.disconnectRequest({terminateDebuggee:e.terminateDebuggee!==!1}),t.server&&t.server.stop(),this.sessions.delete(e.sessionId),{status:"terminated",message:"Debug session stopped"}}catch(s){return this.sessions.delete(e.sessionId),{status:"terminated",message:`Debug session stopped (with error: ${s.message})`}}}getSession(e){return this.sessions.get(e)?.session||null}listSessions(){return Array.from(this.sessions.values()).map(e=>e.session)}generateSessionId(){return `java-debug-${Date.now()}-${++this.sessionIdCounter}`}getSessionContext(e){let t=this.sessions.get(e);if(!t)throw new Error(`Debug session not found: ${e}`);return t}setupClientListeners(e,t){t.on("event",s=>{let n=this.sessions.get(e);if(n){switch(s.event){case "stopped":n.session.status="stopped",n.session.currentThreadId=s.body.threadId,n.session.stoppedReason=s.body.reason,n.session.lastActivity=Date.now();break;case "continued":n.session.status="running",n.session.lastActivity=Date.now();break;case "terminated":n.session.status="terminated",n.session.lastActivity=Date.now();break}this.emit("session:event",{sessionId:e,event:s.event,body:s.body});}});}async waitForStoppedOrTimeout(e,t,s=5e3){return new Promise(n=>{let r=setTimeout(()=>{e.client.off("event:stopped",i),e.client.off("event:terminated",i),n({status:"running",message:"Program is running"});},s),i=o=>{clearTimeout(r),e.client.off("event:stopped",i),e.client.off("event:terminated",i),o.reason?n({status:"stopped",stoppedReason:o.reason,location:o.source?{filePath:o.source.path,line:o.line,column:o.column||0}:void 0,message:`Program stopped: ${o.reason}`}):n({status:"terminated",message:"Program terminated"});};e.client.once("event:stopped",i),e.client.once("event:terminated",i);})}async performStep(e,t){let s=this.getSessionContext(e.sessionId);s.session.lastActivity=Date.now();try{let n=e.threadId||s.session.currentThreadId||1;switch(t){case "stepOver":await s.client.next({threadId:n});break;case "stepInto":await s.client.stepIn({threadId:n});break;case "stepOut":await s.client.stepOut({threadId:n});break}return new Promise((r,i)=>{let o=setTimeout(()=>{i(new Error("Step operation timeout"));},5e3);s.client.once("event:stopped",async l=>{clearTimeout(o);try{let u=(await s.client.stackTrace({threadId:n,startFrame:0,levels:1})).body.stackFrames[0];s.session.currentFrameId=u.id,r({status:"stopped",location:{filePath:u.source?.path||"unknown",line:u.line,method:u.name},message:`Stepped to ${u.name} at line ${u.line}`});}catch(c){i(c);}});})}catch(n){throw new Error(`Failed to perform step: ${n.message}`)}}cleanupInactiveSessions(){if(!this.config.sessionTimeout)return;let e=Date.now();for(let[t,s]of this.sessions.entries())e-s.session.lastActivity>this.config.sessionTimeout&&(console.log(`Cleaning up inactive session: ${t}`),this.stop({sessionId:t}).catch(r=>{console.error(`Failed to stop inactive session ${t}:`,r);}));}};var hf=fileURLToPath(import.meta.url),ff=te.dirname(hf);async function yf(){let a=process,e=[...a.resourcesPath?[te.join(a.resourcesPath,"java-debug","com.microsoft.java.debug.plugin.jar")]:[],te.join(process.cwd(),"resources","java-debug","com.microsoft.java.debug.plugin.jar"),te.join(ff,"..","..","..","resources","java-debug","com.microsoft.java.debug.plugin.jar")];for(let t of e)try{return await ce.access(t),console.log(`\u2713 \u627E\u5230\u5185\u7F6E Java Debug JAR: ${t}`),t}catch{}return null}async function Bu(a){if(a)try{return await ce.access(a),console.log(`\u2713 \u4F7F\u7528\u914D\u7F6E\u7684 Java Debug JAR: ${a}`),a}catch{console.warn(`\u26A0\uFE0F \u914D\u7F6E\u7684 JAR \u8DEF\u5F84\u65E0\u6548: ${a}`);}let e=await yf();if(e)return e;throw new Error(`Java Debug JAR \u672A\u627E\u5230\uFF01
456
456
  \u8BF7\u6267\u884C\u4EE5\u4E0B\u6B65\u9AA4\u4E4B\u4E00\uFF1A
457
457
  1. \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D
458
458
  2. \u5728\u914D\u7F6E\u4E2D\u6307\u5B9A JAR \u8DEF\u5F84
459
- 3. \u624B\u52A8\u4E0B\u8F7D\u5E76\u7F16\u8BD1\uFF1Ahttps://github.com/microsoft/java-debug`)}var Pa=null;function kt(){if(!Pa)throw new Error("Java Debug Session Manager not initialized. Call createJavaDebugTools() first.");return Pa}async function Da(a){let e=await Bu(a);Pa=new ci({javaDebugJarPath:e,defaultTimeout:3e4,maxSessions:5,sessionTimeout:1800*1e3});let t=[yf,bf,vf,wf,Cf,kf,Sf,xf,Tf,_f,Rf],s=["debug"];return t.map(n=>({...n,capabilities:n.capabilities?Array.from(new Set([...n.capabilities,...s])):s}))}var yf={name:"java_debug_launch",description:`Launch a Java application in debug mode.
459
+ 3. \u624B\u52A8\u4E0B\u8F7D\u5E76\u7F16\u8BD1\uFF1Ahttps://github.com/microsoft/java-debug`)}var Pa=null;function kt(){if(!Pa)throw new Error("Java Debug Session Manager not initialized. Call createJavaDebugTools() first.");return Pa}async function Da(a){let e=await Bu(a);Pa=new ci({javaDebugJarPath:e,defaultTimeout:3e4,maxSessions:5,sessionTimeout:1800*1e3});let t=[bf,vf,wf,Cf,kf,Sf,xf,Tf,_f,Rf,Af],s=["debug"];return t.map(n=>({...n,capabilities:n.capabilities?Array.from(new Set([...n.capabilities,...s])):s}))}var bf={name:"java_debug_launch",description:`Launch a Java application in debug mode.
460
460
 
461
461
  Use this tool when you need to start debugging a Java program from the beginning.
462
462
 
@@ -465,7 +465,7 @@ Examples:
465
465
  - Debug a standalone Java program
466
466
  - Debug with specific JVM arguments or classpath
467
467
 
468
- After launching, you'll receive a sessionId that you must use for all subsequent debug operations.`,parameters:{type:"object",properties:{mainClass:{type:"string",description:'The fully qualified main class name (e.g., "com.example.Main", "org.springframework.boot.SpringApplication")'},projectPath:{type:"string",description:"The absolute path to the Java project root directory"},classpath:{type:"string",description:"Optional classpath for the application (JAR files, directories)"},args:{type:"array",items:{type:"string"},description:'Optional program arguments (e.g., ["--port", "8080", "--debug"])'},vmArgs:{type:"array",items:{type:"string"},description:'Optional JVM arguments (e.g., ["-Xmx512m", "-Dspring.profiles.active=dev"])'},stopOnEntry:{type:"boolean",description:"Stop at the entry point (main method). Default: false"},cwd:{type:"string",description:"Working directory for the application. Default: projectPath"}},required:["mainClass","projectPath"]},async function(a){try{let t=await kt().launch(a);return JSON.stringify({success:!0,sessionId:t.sessionId,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},bf={name:"java_debug_attach",description:`Attach to a running Java process for debugging.
468
+ After launching, you'll receive a sessionId that you must use for all subsequent debug operations.`,parameters:{type:"object",properties:{mainClass:{type:"string",description:'The fully qualified main class name (e.g., "com.example.Main", "org.springframework.boot.SpringApplication")'},projectPath:{type:"string",description:"The absolute path to the Java project root directory"},classpath:{type:"string",description:"Optional classpath for the application (JAR files, directories)"},args:{type:"array",items:{type:"string"},description:'Optional program arguments (e.g., ["--port", "8080", "--debug"])'},vmArgs:{type:"array",items:{type:"string"},description:'Optional JVM arguments (e.g., ["-Xmx512m", "-Dspring.profiles.active=dev"])'},stopOnEntry:{type:"boolean",description:"Stop at the entry point (main method). Default: false"},cwd:{type:"string",description:"Working directory for the application. Default: projectPath"}},required:["mainClass","projectPath"]},async function(a){try{let t=await kt().launch(a);return JSON.stringify({success:!0,sessionId:t.sessionId,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},vf={name:"java_debug_attach",description:`Attach to a running Java process for debugging.
469
469
 
470
470
  Use this tool when the Java application is already running with JDWP enabled.
471
471
 
@@ -477,7 +477,7 @@ Common JDWP ports:
477
477
  - 8000
478
478
  - Custom port specified by the application
479
479
 
480
- After attaching, you'll receive a sessionId for all subsequent debug operations.`,parameters:{type:"object",properties:{port:{type:"number",description:"The JDWP port number (usually 5005 or 8000)"},hostName:{type:"string",description:'The hostname to connect to. Default: "localhost"'},timeout:{type:"number",description:"Connection timeout in milliseconds. Default: 5000"}},required:["port"]},async function(a){try{let t=await kt().attach(a);return JSON.stringify({success:!0,sessionId:t.sessionId,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},vf={name:"java_debug_set_breakpoint",description:`Set a breakpoint at a specific line in a Java source file.
480
+ After attaching, you'll receive a sessionId for all subsequent debug operations.`,parameters:{type:"object",properties:{port:{type:"number",description:"The JDWP port number (usually 5005 or 8000)"},hostName:{type:"string",description:'The hostname to connect to. Default: "localhost"'},timeout:{type:"number",description:"Connection timeout in milliseconds. Default: 5000"}},required:["port"]},async function(a){try{let t=await kt().attach(a);return JSON.stringify({success:!0,sessionId:t.sessionId,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},wf={name:"java_debug_set_breakpoint",description:`Set a breakpoint at a specific line in a Java source file.
481
481
 
482
482
  The program will pause when execution reaches this line, allowing you to inspect variables and stack trace.
483
483
 
@@ -489,7 +489,7 @@ You can set:
489
489
 
490
490
  Examples:
491
491
  - Set breakpoint at line 25: {"sessionId": "...", "filePath": "/path/Main.java", "line": 25}
492
- - Conditional breakpoint: {"sessionId": "...", "filePath": "/path/Main.java", "line": 30, "condition": "count > 10"}`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID from java_debug_launch or java_debug_attach"},filePath:{type:"string",description:"The absolute path to the Java source file"},line:{type:"number",description:"The line number where to set the breakpoint (1-indexed)"},condition:{type:"string",description:'Optional condition expression (e.g., "count > 10", "user != null"). Breakpoint only triggers when condition is true.'},hitCondition:{type:"string",description:'Optional hit condition (e.g., ">5", "==3"). Breakpoint triggers after this many hits.'},logMessage:{type:"string",description:"Optional log message (logpoint). The breakpoint will log this message instead of pausing. Use {variable} for interpolation."}},required:["sessionId","filePath","line"]},async function(a){try{let t=await kt().setBreakpoint(a);return JSON.stringify({success:!0,breakpointId:t.breakpointId,verified:t.verified,line:t.line,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},wf={name:"java_debug_continue",description:`Continue program execution until the next breakpoint or program termination.
492
+ - Conditional breakpoint: {"sessionId": "...", "filePath": "/path/Main.java", "line": 30, "condition": "count > 10"}`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID from java_debug_launch or java_debug_attach"},filePath:{type:"string",description:"The absolute path to the Java source file"},line:{type:"number",description:"The line number where to set the breakpoint (1-indexed)"},condition:{type:"string",description:'Optional condition expression (e.g., "count > 10", "user != null"). Breakpoint only triggers when condition is true.'},hitCondition:{type:"string",description:'Optional hit condition (e.g., ">5", "==3"). Breakpoint triggers after this many hits.'},logMessage:{type:"string",description:"Optional log message (logpoint). The breakpoint will log this message instead of pausing. Use {variable} for interpolation."}},required:["sessionId","filePath","line"]},async function(a){try{let t=await kt().setBreakpoint(a);return JSON.stringify({success:!0,breakpointId:t.breakpointId,verified:t.verified,line:t.line,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Cf={name:"java_debug_continue",description:`Continue program execution until the next breakpoint or program termination.
493
493
 
494
494
  Use this tool to:
495
495
  - Resume execution after hitting a breakpoint
@@ -504,7 +504,7 @@ The tool will return:
504
504
  When the program stops at a breakpoint, you can then use:
505
505
  - java_debug_get_variables to inspect variables
506
506
  - java_debug_get_stack_trace to see the call stack
507
- - java_debug_evaluate to test expressions`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().continue(a);return JSON.stringify({success:!0,status:t.status,stoppedReason:t.stoppedReason,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Cf={name:"java_debug_step_over",description:`Execute the current line and move to the next line (step over).
507
+ - java_debug_evaluate to test expressions`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().continue(a);return JSON.stringify({success:!0,status:t.status,stoppedReason:t.stoppedReason,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},kf={name:"java_debug_step_over",description:`Execute the current line and move to the next line (step over).
508
508
 
509
509
  If the current line contains a method call, the entire method executes without stopping inside it.
510
510
 
@@ -516,7 +516,7 @@ Use this when:
516
516
  Example workflow:
517
517
  1. Set breakpoint at line 20
518
518
  2. Continue execution (stops at line 20)
519
- 3. Step over to line 21, 22, 23... until you find the issue`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().stepOver(a);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},kf={name:"java_debug_step_into",description:`Execute the current line and step into method calls.
519
+ 3. Step over to line 21, 22, 23... until you find the issue`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().stepOver(a);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Sf={name:"java_debug_step_into",description:`Execute the current line and step into method calls.
520
520
 
521
521
  If the current line contains a method call, execution stops at the first line inside that method.
522
522
 
@@ -528,7 +528,7 @@ Use this when:
528
528
  Example:
529
529
  Line 20: result = processData(input);
530
530
 
531
- After step into, you'll be inside processData() at its first line.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().stepInto(a);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Sf={name:"java_debug_step_out",description:`Execute until the current method returns (step out).
531
+ After step into, you'll be inside processData() at its first line.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().stepInto(a);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},xf={name:"java_debug_step_out",description:`Execute until the current method returns (step out).
532
532
 
533
533
  Execution continues until the current method completes and returns to its caller.
534
534
 
@@ -539,7 +539,7 @@ Use this when:
539
539
 
540
540
  Example:
541
541
  You're at line 15 inside processData() method.
542
- After step out, you'll be at the line that called processData().`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().stepOut(a);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},xf={name:"java_debug_get_variables",description:`Get the values of variables in the current scope.
542
+ After step out, you'll be at the line that called processData().`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().stepOut(a);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Tf={name:"java_debug_get_variables",description:`Get the values of variables in the current scope.
543
543
 
544
544
  Use this tool when the program is paused (at a breakpoint or after stepping) to inspect:
545
545
  - Local variables
@@ -558,7 +558,7 @@ Example use case:
558
558
  1. Program stops at breakpoint line 25
559
559
  2. Call java_debug_get_variables to see all variable values
560
560
  3. Analyze which variables have unexpected values
561
- 4. Identify the bug!`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},frameId:{type:"number",description:"Optional stack frame ID. Default: current frame (0 = topmost frame)"},filter:{type:"string",enum:["local","arguments","all"],description:'Filter variables by type. Default: "all"'}},required:["sessionId"]},async function(a){try{let t=await kt().getVariables(a);return JSON.stringify({success:!0,variables:t.variables,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Tf={name:"java_debug_get_stack_trace",description:`Get the current call stack (stack trace).
561
+ 4. Identify the bug!`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},frameId:{type:"number",description:"Optional stack frame ID. Default: current frame (0 = topmost frame)"},filter:{type:"string",enum:["local","arguments","all"],description:'Filter variables by type. Default: "all"'}},required:["sessionId"]},async function(a){try{let t=await kt().getVariables(a);return JSON.stringify({success:!0,variables:t.variables,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},_f={name:"java_debug_get_stack_trace",description:`Get the current call stack (stack trace).
562
562
 
563
563
  The stack trace shows the sequence of method calls that led to the current point of execution.
564
564
 
@@ -577,7 +577,7 @@ Frame 2: The method that called Frame 1
577
577
  Example output:
578
578
  Frame 0: processUser() at UserService.java:42
579
579
  Frame 1: handleRequest() at RequestHandler.java:28
580
- Frame 2: main() at Main.java:15`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().getStackTrace(a);return JSON.stringify({success:!0,stackFrames:t.stackFrames,totalFrames:t.totalFrames,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},_f={name:"java_debug_evaluate",description:`Evaluate a Java expression in the current debug context.
580
+ Frame 2: main() at Main.java:15`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(a){try{let t=await kt().getStackTrace(a);return JSON.stringify({success:!0,stackFrames:t.stackFrames,totalFrames:t.totalFrames,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Rf={name:"java_debug_evaluate",description:`Evaluate a Java expression in the current debug context.
581
581
 
582
582
  This is an extremely powerful tool that lets you:
583
583
  - Check variable values with custom logic
@@ -600,13 +600,13 @@ Example debugging workflow:
600
600
  2. Evaluate: "user != null" -> false
601
601
  3. Look at stack trace to see where user was initialized
602
602
  4. Evaluate: "getUserFromCache(userId)" to test if cache has the user
603
- 5. Identify that cache lookup is failing`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},expression:{type:"string",description:'The Java expression to evaluate (e.g., "user.getName()", "count > 10", "items.size()")'},frameId:{type:"number",description:"Optional stack frame ID. Default: current frame"},context:{type:"string",enum:["watch","repl","hover"],description:'Evaluation context. Default: "repl"'}},required:["sessionId","expression"]},async function(a){try{let t=await kt().evaluate(a);return JSON.stringify({success:!0,result:t.result,type:t.type,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Rf={name:"java_debug_stop",description:`Stop the debug session and optionally terminate the debugged program.
603
+ 5. Identify that cache lookup is failing`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},expression:{type:"string",description:'The Java expression to evaluate (e.g., "user.getName()", "count > 10", "items.size()")'},frameId:{type:"number",description:"Optional stack frame ID. Default: current frame"},context:{type:"string",enum:["watch","repl","hover"],description:'Evaluation context. Default: "repl"'}},required:["sessionId","expression"]},async function(a){try{let t=await kt().evaluate(a);return JSON.stringify({success:!0,result:t.result,type:t.type,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},Af={name:"java_debug_stop",description:`Stop the debug session and optionally terminate the debugged program.
604
604
 
605
605
  Always call this tool when you're done debugging to clean up resources.
606
606
 
607
607
  By default, this will terminate the debugged program. Set terminateDebuggee=false to disconnect without killing the program.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},terminateDebuggee:{type:"boolean",description:"Whether to terminate the debugged program. Default: true"}},required:["sessionId"]},async function(a){try{let t=await kt().stop(a);return JSON.stringify({success:!0,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}};var Gu={enabled:false,autoPrompt:true,languages:["typescript","javascript","python","java","go","rust"],include:["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py","**/*.java","**/*.go","**/*.rs"],exclude:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/__pycache__/**","**/target/**","**/vendor/**"],cacheDir:".neox/index",maxFileSize:5},$n=200,ui=10,Fn=4e3,qs=700;function Uu(a){return createHash("md5").update(a).digest("hex")}async function Wu(a){try{return await ce.access(a),!0}catch{return false}}async function jn(a){try{await ce.mkdir(a,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async function La(a,e,t){let n=(await ce.readFile(a,"utf-8")).split(`
608
608
  `),r=n.length,i=Math.max(0,e-1),o=Math.min(n.length,t);return {lines:n.slice(i,o),totalLines:r}}function ze(a,e){return a.map((t,s)=>`${String(e+s).padStart(6)} \u2502 ${t}`).join(`
609
- `)}function Js(a,e){let s=te.relative(e,a).split(te.sep),n=s.findIndex(r=>["src","lib","app","core","packages","modules"].includes(r));return n>=0&&n+1<s.length?s[n+1]:s[0]||"root"}function Oa(a){let e=te.extname(a).toLowerCase();return {".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".go":"go",".rs":"rust",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".scala":"scala",".vue":"vue",".svelte":"svelte"}[e]||null}function Zt(a,e,t="{([",s="})]"){let n=[],r=false;for(let i=e;i<a.length;i++){let o=a[i];for(let l of o){let c=t.indexOf(l),u=s.indexOf(l);c!==-1?(n.push(s[c]),r=true):u!==-1&&n.length>0&&n[n.length-1]===l&&n.pop();}if(r&&n.length===0)return i+1}return Math.min(e+500,a.length)}function qu(a,e,t=["^\\s*(export\\s+)?(async\\s+)?function\\s+","^\\s*(export\\s+)?class\\s+","^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?\\(","^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?function","^\\s*(public|private|protected|static|async)*\\s*\\w+\\s*\\(","^\\s*def\\s+","^\\s*class\\s+","^\\s*func\\s+","^\\s*fn\\s+"]){let s=t.map(n=>new RegExp(n));for(let n=e;n>=0;n--){let r=a[n];for(let i of s)if(i.test(r))return n;if(n<e&&r.trim()===""){let i=a.slice(0,n).reverse().findIndex(o=>o.trim()!=="");if(i>=0){let o=a[n-1-i];if(!o.trim().startsWith("@")&&!o.trim().startsWith("#")&&!o.trim().startsWith("//")&&!o.trim().startsWith("/*"))break}}}return Math.max(0,e-5)}function Na(a,e){let t=a.length>e.length?a:e,s=a.length>e.length?e:a;if(t.length===0)return 1;let n=Ef(t,s);return (t.length-n)/t.length}function Ef(a,e){let t=a.length,s=e.length,n=Array(t+1).fill(null).map(()=>Array(s+1).fill(0));for(let r=0;r<=t;r++)n[r][0]=r;for(let r=0;r<=s;r++)n[0][r]=r;for(let r=1;r<=t;r++)for(let i=1;i<=s;i++)a[r-1]===e[i-1]?n[r][i]=n[r-1][i-1]:n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+1);return n[t][s]}function Ks(a){return a.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}var di=class{workspacePath;indexManager=null;constructor(e){this.workspacePath=e;}setIndexManager(e){this.indexManager=e;}async read(e){let{path:t,locator:s,mode:n="smart",autoFullThreshold:r,chunkSize:i=$n,expandContext:o=ui,maxLines:l=Fn,useIndex:c=true}=e;try{let u=this.resolvePath(t);if((await ce.stat(u)).isDirectory())return this.errorResult(t,"\u8FD9\u662F\u4E00\u4E2A\u76EE\u5F55\uFF0C\u4E0D\u662F\u6587\u4EF6");switch(n){case "full":return this.readFull(u,t,l);case "chunk":return !s||s.type!=="line"?this.readChunk(u,t,1,i):this.readChunk(u,t,s.start,s.end?s.end-s.start+1:i);default:return this.smartRead(u,t,s,{autoFullThreshold:r,chunkSize:i,expandContext:o,maxLines:l,useIndex:c})}}catch(u){return u.code==="ENOENT"?this.errorResult(t,"\u6587\u4EF6\u4E0D\u5B58\u5728"):this.errorResult(t,u.message)}}async smartRead(e,t,s,n){let{autoFullThreshold:r,chunkSize:i,expandContext:o,maxLines:l,useIndex:c}=n;if(!s){if(typeof r=="number"&&r>0){let u=await ce.readFile(e,"utf-8"),d=Ks(u).split(`
609
+ `)}function Js(a,e){let s=te.relative(e,a).split(te.sep),n=s.findIndex(r=>["src","lib","app","core","packages","modules"].includes(r));return n>=0&&n+1<s.length?s[n+1]:s[0]||"root"}function Oa(a){let e=te.extname(a).toLowerCase();return {".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".go":"go",".rs":"rust",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".scala":"scala",".vue":"vue",".svelte":"svelte"}[e]||null}function Zt(a,e,t="{([",s="})]"){let n=[],r=false;for(let i=e;i<a.length;i++){let o=a[i];for(let l of o){let c=t.indexOf(l),u=s.indexOf(l);c!==-1?(n.push(s[c]),r=true):u!==-1&&n.length>0&&n[n.length-1]===l&&n.pop();}if(r&&n.length===0)return i+1}return Math.min(e+500,a.length)}function qu(a,e,t=["^\\s*(export\\s+)?(async\\s+)?function\\s+","^\\s*(export\\s+)?class\\s+","^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?\\(","^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?function","^\\s*(public|private|protected|static|async)*\\s*\\w+\\s*\\(","^\\s*def\\s+","^\\s*class\\s+","^\\s*func\\s+","^\\s*fn\\s+"]){let s=t.map(n=>new RegExp(n));for(let n=e;n>=0;n--){let r=a[n];for(let i of s)if(i.test(r))return n;if(n<e&&r.trim()===""){let i=a.slice(0,n).reverse().findIndex(o=>o.trim()!=="");if(i>=0){let o=a[n-1-i];if(!o.trim().startsWith("@")&&!o.trim().startsWith("#")&&!o.trim().startsWith("//")&&!o.trim().startsWith("/*"))break}}}return Math.max(0,e-5)}function Na(a,e){let t=a.length>e.length?a:e,s=a.length>e.length?e:a;if(t.length===0)return 1;let n=If(t,s);return (t.length-n)/t.length}function If(a,e){let t=a.length,s=e.length,n=Array(t+1).fill(null).map(()=>Array(s+1).fill(0));for(let r=0;r<=t;r++)n[r][0]=r;for(let r=0;r<=s;r++)n[0][r]=r;for(let r=1;r<=t;r++)for(let i=1;i<=s;i++)a[r-1]===e[i-1]?n[r][i]=n[r-1][i-1]:n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+1);return n[t][s]}function Ks(a){return a.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}var di=class{workspacePath;indexManager=null;constructor(e){this.workspacePath=e;}setIndexManager(e){this.indexManager=e;}async read(e){let{path:t,locator:s,mode:n="smart",autoFullThreshold:r,chunkSize:i=$n,expandContext:o=ui,maxLines:l=Fn,useIndex:c=true}=e;try{let u=this.resolvePath(t);if((await ce.stat(u)).isDirectory())return this.errorResult(t,"\u8FD9\u662F\u4E00\u4E2A\u76EE\u5F55\uFF0C\u4E0D\u662F\u6587\u4EF6");switch(n){case "full":return this.readFull(u,t,l);case "chunk":return !s||s.type!=="line"?this.readChunk(u,t,1,i):this.readChunk(u,t,s.start,s.end?s.end-s.start+1:i);default:return this.smartRead(u,t,s,{autoFullThreshold:r,chunkSize:i,expandContext:o,maxLines:l,useIndex:c})}}catch(u){return u.code==="ENOENT"?this.errorResult(t,"\u6587\u4EF6\u4E0D\u5B58\u5728"):this.errorResult(t,u.message)}}async smartRead(e,t,s,n){let{autoFullThreshold:r,chunkSize:i,expandContext:o,maxLines:l,useIndex:c}=n;if(!s){if(typeof r=="number"&&r>0){let u=await ce.readFile(e,"utf-8"),d=Ks(u).split(`
610
610
  `),p=d.length;if(p<=r){let f=Math.min(p,l),b=d.slice(0,f);return {success:true,path:t,totalLines:p,startLine:1,endLine:f,content:ze(b,1),truncated:f<p,strategy:"full"}}let h=Math.min(i,p),g=d.slice(0,h);return {success:true,path:t,totalLines:p,startLine:1,endLine:h,content:ze(g,1),truncated:h<p,strategy:"chunk"}}return this.readChunk(e,t,1,i)}switch(s.type){case "line":return this.readByLine(e,t,s.start,s.end,i);case "pattern":return this.readByPattern(e,t,s.regex,{matchIndex:s.matchIndex||1,context:s.context||o,chunkSize:i});case "symbol":return this.readBySymbol(e,t,s.name,{kind:s.kind,fuzzy:s.fuzzy,chunkSize:i,useIndex:c});case "function":return this.readBySymbol(e,t,s.name,{kind:"function",className:s.className,chunkSize:i,useIndex:c});case "class":return this.readBySymbol(e,t,s.name,{kind:"class",chunkSize:i,useIndex:c});case "range":return this.readByRange(e,t,s.startPattern,s.endPattern,i);default:return this.readChunk(e,t,1,i)}}async readByLine(e,t,s,n,r){let i=n||s+r-1,{lines:o,totalLines:l}=await La(e,s,i);return {success:true,path:t,totalLines:l,startLine:s,endLine:Math.min(i,l),content:ze(o,s),truncated:i<l,strategy:"chunk"}}async readByPattern(e,t,s,n){let{matchIndex:r,context:i,chunkSize:o}=n,c=(await ce.readFile(e,"utf-8")).split(`
611
611
  `),u=c.length,d;try{d=new RegExp(s,"gi");}catch(y){return this.errorResult(t,`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${y.message}`)}let p=[];if(c.forEach((y,w)=>{d.test(y)&&p.push(w+1),d.lastIndex=0;}),p.length===0)return {success:true,path:t,totalLines:u,startLine:1,endLine:Math.min(o,u),content:`\u672A\u627E\u5230\u5339\u914D: "${s}"
612
612
 
@@ -618,17 +618,17 @@ By default, this will terminate the debugged program. Set terminateDebuggee=fals
618
618
 
619
619
  `+ze(o.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};p===-1&&(p=Math.min(d+r-1,l-1));let h=Math.min(p+1,d+r),g=o.slice(d,h);return {success:true,path:t,totalLines:l,startLine:d+1,endLine:h,content:ze(g,d+1),truncated:h<p+1,strategy:"grep",metadata:{module:Js(e,this.workspacePath)}}}async readChunk(e,t,s,n){let r=await ce.readFile(e,"utf-8"),i=Ks(r).split(`
620
620
  `),o=i.length,l=Math.max(1,s),c=Math.min(l+n-1,o),u=i.slice(l-1,c);return {success:true,path:t,totalLines:o,startLine:l,endLine:c,content:ze(u,l),truncated:c<o,strategy:"chunk"}}async readFull(e,t,s){let n=await ce.readFile(e,"utf-8"),r=Ks(n).split(`
621
- `),i=r.length,o=Math.min(i,s),l=r.slice(0,o);return {success:true,path:t,totalLines:i,startLine:1,endLine:o,content:ze(l,1),truncated:o<i,strategy:"full"}}buildSymbolPattern(e,t,s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r={function:`(function|async\\s+function|const|let|var)\\s+${n}\\s*[=(<]`,class:`class\\s+${n}(\\s+extends|\\s+implements|\\s*\\{|\\s*$)`,interface:`interface\\s+${n}(\\s+extends|\\s*\\{|\\s*$)`,method:s?`(${n}|${s}\\.${n})\\s*\\(`:`${n}\\s*\\(`,variable:`(const|let|var)\\s+${n}\\s*[=:]`,type:`type\\s+${n}\\s*[=<]`,enum:`enum\\s+${n}\\s*\\{`,constant:`(const|final|static\\s+final)\\s+[A-Z_]+\\s*${n}`};return t&&r[t]?r[t]:`(function|class|interface|type|enum|const|let|var|def|fn|func)\\s+${n}|${n}\\s*(=|\\()`}resolvePath(e){return te.isAbsolute(e)?e:te.resolve(this.workspacePath,e)}errorResult(e,t){return {success:false,path:e,totalLines:0,startLine:0,endLine:0,content:"",truncated:false,strategy:"chunk",error:t}}};function $a(a){return new di(a)}var dd=dg(nd());var Gn=a=>{if(typeof a!="string")throw new TypeError("invalid pattern");if(a.length>65536)throw new TypeError("pattern is too long")};var $f={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},Un=a=>a.replace(/[[\]\\-]/g,"\\$&"),Ff=a=>a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),rd=a=>a.join(""),id=(a,e)=>{let t=e;if(a.charAt(t)!=="[")throw new Error("not in a brace expression");let s=[],n=[],r=t+1,i=false,o=false,l=false,c=false,u=t,d="";e:for(;r<a.length;){let f=a.charAt(r);if((f==="!"||f==="^")&&r===t+1){c=true,r++;continue}if(f==="]"&&i&&!l){u=r+1;break}if(i=true,f==="\\"&&!l){l=true,r++;continue}if(f==="["&&!l){for(let[b,[y,w,C]]of Object.entries($f))if(a.startsWith(b,r)){if(d)return ["$.",false,a.length-t,true];r+=b.length,C?n.push(y):s.push(y),o=o||w;continue e}}if(l=false,d){f>d?s.push(Un(d)+"-"+Un(f)):f===d&&s.push(Un(f)),d="",r++;continue}if(a.startsWith("-]",r+1)){s.push(Un(f+"-")),r+=2;continue}if(a.startsWith("-",r+1)){d=f,r+=2;continue}s.push(Un(f)),r++;}if(u<r)return ["",false,0,false];if(!s.length&&!n.length)return ["$.",false,a.length-t,true];if(n.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let f=s[0].length===2?s[0].slice(-1):s[0];return [Ff(f),false,u-t,false]}let p="["+(c?"^":"")+rd(s)+"]",h="["+(c?"":"^")+rd(n)+"]";return [s.length&&n.length?"("+p+"|"+h+")":s.length?p:h,o,u-t,true]};var St=(a,{windowsPathsNoEscape:e=false}={})=>e?a.replace(/\[([^\/\\])\]/g,"$1"):a.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var jf=new Set(["!","?","+","*","@"]),od=a=>jf.has(a),Bf="(?!(?:^|/)\\.\\.?(?:$|/))",mi="(?!\\.)",Gf=new Set(["[","."]),Uf=new Set(["..","."]),Wf=new Set("().*{}+?[]^$\\!"),qf=a=>a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ba="[^/]",ad=Ba+"*?",ld=Ba+"+?",Vs=class a{type;#e;#t;#i=false;#n=[];#o;#w;#c;#d=false;#a;#l;#r=false;constructor(e,t,s={}){this.type=e,e&&(this.#t=true),this.#o=t,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#d&&this.#c.push(this),this.#w=this.#o?this.#o.#n.length:0;}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#n)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=true;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#n.map(e=>String(e)).join("|")+")":this.#l=this.#n.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#d)return this;this.toString(),this.#d=true;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,s=t.#o;for(;s;){for(let n=t.#w+1;!s.type&&n<s.#n.length;n++)for(let r of e.#n){if(typeof r=="string")throw new Error("string part in extglob AST??");r.copyIn(s.#n[n]);}t=s,s=t.#o;}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof a&&t.#o===this))throw new Error("invalid part: "+t);this.#n.push(t);}}toJSON(){let e=this.type===null?this.#n.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#n.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#d&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return true;if(!this.#o?.isStart())return false;if(this.#w===0)return true;let e=this.#o;for(let t=0;t<this.#w;t++){let s=e.#n[t];if(!(s instanceof a&&s.type==="!"))return false}return true}isEnd(){if(this.#e===this||this.#o?.type==="!")return true;if(!this.#o?.isEnd())return false;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#n.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this));}clone(e){let t=new a(this.type,e);for(let s of this.#n)t.copyIn(s);return t}static#y(e,t,s,n){let r=false,i=false,o=-1,l=false;if(t.type===null){let h=s,g="";for(;h<e.length;){let f=e.charAt(h++);if(r||f==="\\"){r=!r,g+=f;continue}if(i){h===o+1?(f==="^"||f==="!")&&(l=true):f==="]"&&!(h===o+2&&l)&&(i=false),g+=f;continue}else if(f==="["){i=true,o=h,l=false,g+=f;continue}if(!n.noext&&od(f)&&e.charAt(h)==="("){t.push(g),g="";let b=new a(f,t);h=a.#y(e,b,h,n),t.push(b);continue}g+=f;}return t.push(g),h}let c=s+1,u=new a(null,t),d=[],p="";for(;c<e.length;){let h=e.charAt(c++);if(r||h==="\\"){r=!r,p+=h;continue}if(i){c===o+1?(h==="^"||h==="!")&&(l=true):h==="]"&&!(c===o+2&&l)&&(i=false),p+=h;continue}else if(h==="["){i=true,o=c,l=false,p+=h;continue}if(od(h)&&e.charAt(c)==="("){u.push(p),p="";let g=new a(h,u);u.push(g),c=a.#y(e,g,c,n);continue}if(h==="|"){u.push(p),p="",d.push(u),u=new a(null,t);continue}if(h===")")return p===""&&t.#n.length===0&&(t.#r=true),u.push(p),p="",t.push(...d,u),c;p+=h;}return t.type=null,t.#t=void 0,t.#n=[e.substring(s-1)],c}static fromGlob(e,t={}){let s=new a(null,void 0,t);return a.#y(e,s,0,t),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,s,n,r]=this.toRegExpSource();if(!(n||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(r?"u":"");return Object.assign(new RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#n.map(h=>{let[g,f,b,y]=typeof h=="string"?a.#p(h,this.#t,l):h.toRegExpSource(e);return this.#t=this.#t||b,this.#i=this.#i||y,g}).join(""),u="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&Uf.has(this.#n[0]))){let g=Gf,f=t&&g.has(c.charAt(0))||c.startsWith("\\.")&&g.has(c.charAt(2))||c.startsWith("\\.\\.")&&g.has(c.charAt(4)),b=!t&&!e&&g.has(c.charAt(0));u=f?Bf:b?mi:"";}let d="";return this.isEnd()&&this.#e.#d&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,St(c),this.#t=!!this.#t,this.#i]}let s=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#m(t);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#t=void 0,[l,St(this.toString()),false,false]}let i=!s||e||t||!mi?"":this.#m(true);i===r&&(i=""),i&&(r=`(?:${r})(?:${i})*?`);let o="";if(this.type==="!"&&this.#r)o=(this.isStart()&&!t?mi:"")+ld;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?mi:"")+ad+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;o=n+r+l;}return [o,St(r),this.#t=!!this.#t,this.#i]}#m(e){return this.#n.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[s,n,r,i]=t.toRegExpSource(e);return this.#i=this.#i||i,s}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#p(e,t,s=false){let n=false,r="",i=false;for(let o=0;o<e.length;o++){let l=e.charAt(o);if(n){n=false,r+=(Wf.has(l)?"\\":"")+l;continue}if(l==="\\"){o===e.length-1?r+="\\\\":n=true;continue}if(l==="["){let[c,u,d,p]=id(e,o);if(d){r+=c,i=i||u,o+=d-1,t=t||p;continue}}if(l==="*"){s&&e==="*"?r+=ld:r+=ad,t=true;continue}if(l==="?"){r+=Ba,t=true;continue}r+=qf(l);}return [r,St(e),!!t,i]}};var Ys=(a,{windowsPathsNoEscape:e=false}={})=>e?a.replace(/[?*()[\]]/g,"[$&]"):a.replace(/[?*()[\]\\]/g,"\\$&");var Xe=(a,e,t={})=>(Gn(e),!t.nocomment&&e.charAt(0)==="#"?false:new ct(e,t).match(a)),zf=/^\*+([^+@!?\*\[\(]*)$/,Hf=a=>e=>!e.startsWith(".")&&e.endsWith(a),Jf=a=>e=>e.endsWith(a),Kf=a=>(a=a.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(a)),Vf=a=>(a=a.toLowerCase(),e=>e.toLowerCase().endsWith(a)),Yf=/^\*+\.\*+$/,Xf=a=>!a.startsWith(".")&&a.includes("."),Qf=a=>a!=="."&&a!==".."&&a.includes("."),Zf=/^\.\*+$/,ey=a=>a!=="."&&a!==".."&&a.startsWith("."),ty=/^\*+$/,sy=a=>a.length!==0&&!a.startsWith("."),ny=a=>a.length!==0&&a!=="."&&a!=="..",ry=/^\?+([^+@!?\*\[\(]*)?$/,iy=([a,e=""])=>{let t=pd([a]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},oy=([a,e=""])=>{let t=md([a]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},ay=([a,e=""])=>{let t=md([a]);return e?s=>t(s)&&s.endsWith(e):t},ly=([a,e=""])=>{let t=pd([a]);return e?s=>t(s)&&s.endsWith(e):t},pd=([a])=>{let e=a.length;return t=>t.length===e&&!t.startsWith(".")},md=([a])=>{let e=a.length;return t=>t.length===e&&t!=="."&&t!==".."},gd=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",cd={win32:{sep:"\\"},posix:{sep:"/"}},cy=gd==="win32"?cd.win32.sep:cd.posix.sep;Xe.sep=cy;var Ge=Symbol("globstar **");Xe.GLOBSTAR=Ge;var uy="[^/]",dy=uy+"*?",py="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",my="(?:(?!(?:\\/|^)\\.).)*?",gy=(a,e={})=>t=>Xe(t,a,e);Xe.filter=gy;var pt=(a,e={})=>Object.assign({},a,e),hy=a=>{if(!a||typeof a!="object"||!Object.keys(a).length)return Xe;let e=Xe;return Object.assign((s,n,r={})=>e(s,n,pt(a,r)),{Minimatch:class extends e.Minimatch{constructor(n,r={}){super(n,pt(a,r));}static defaults(n){return e.defaults(pt(a,n)).Minimatch}},AST:class extends e.AST{constructor(n,r,i={}){super(n,r,pt(a,i));}static fromGlob(n,r={}){return e.AST.fromGlob(n,pt(a,r))}},unescape:(s,n={})=>e.unescape(s,pt(a,n)),escape:(s,n={})=>e.escape(s,pt(a,n)),filter:(s,n={})=>e.filter(s,pt(a,n)),defaults:s=>e.defaults(pt(a,s)),makeRe:(s,n={})=>e.makeRe(s,pt(a,n)),braceExpand:(s,n={})=>e.braceExpand(s,pt(a,n)),match:(s,n,r={})=>e.match(s,n,pt(a,r)),sep:e.sep,GLOBSTAR:Ge})};Xe.defaults=hy;var hd=(a,e={})=>(Gn(a),e.nobrace||!/\{(?:(?!\{).)*\}/.test(a)?[a]:(0, dd.default)(a));Xe.braceExpand=hd;var fy=(a,e={})=>new ct(a,e).makeRe();Xe.makeRe=fy;var yy=(a,e,t={})=>{let s=new ct(e,t);return a=a.filter(n=>s.match(n)),s.options.nonull&&!a.length&&a.push(e),a};Xe.match=yy;var ud=/[?*]|[+@!]\(.*?\)|\[|\]/,by=a=>a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ct=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Gn(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||gd,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let n=this.globParts.map((r,i,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=r[0]===""&&r[1]===""&&(r[2]==="?"||!ud.test(r[2]))&&!ud.test(r[3]),c=/^[a-z]:/i.test(r[0]);if(l)return [...r.slice(0,4),...r.slice(4).map(u=>this.parse(u))];if(c)return [r[0],...r.slice(1).map(u=>this.parse(u))]}return r.map(l=>this.parse(l))});if(this.debug(this.pattern,n),this.set=n.filter(r=>r.indexOf(false)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){let i=this.set[r];i[0]===""&&i[1]===""&&this.globParts[r][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let s=0;s<e.length;s++)for(let n=0;n<e[s].length;n++)e[s][n]==="**"&&(e[s][n]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let s=-1;for(;(s=t.indexOf("**",s+1))!==-1;){let n=s;for(;t[n+1]==="**";)n++;n!==s&&t.splice(s,n-s);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((s,n)=>{let r=s[s.length-1];return n==="**"&&r==="**"?s:n===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(n),s)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===""&&e[0]===""||(r==="."||r==="")&&(t=true,e.splice(n,1),n--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let s=0;for(;(s=e.indexOf("..",s+1))!==-1;){let n=e[s-1];n&&n!=="."&&n!==".."&&n!=="**"&&(t=true,e.splice(s-1,2),s-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let s of e){let n=-1;for(;(n=s.indexOf("**",n+1))!==-1;){let i=n;for(;s[i+1]==="**";)i++;i>n&&s.splice(n+1,i-n);let o=s[n+1],l=s[n+2],c=s[n+3];if(o!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=true,s.splice(n,1);let u=s.slice(0);u[n]="**",e.push(u),n--;}if(!this.preserveMultipleSlashes){for(let i=1;i<s.length-1;i++){let o=s[i];i===1&&o===""&&s[0]===""||(o==="."||o==="")&&(t=true,s.splice(i,1),i--);}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(t=true,s.pop());}let r=0;for(;(r=s.indexOf("..",r+1))!==-1;){let i=s[r-1];if(i&&i!=="."&&i!==".."&&i!=="**"){t=true;let l=r===1&&s[r+1]==="**"?["."]:[];s.splice(r-1,2,...l),s.length===0&&s.push(""),r-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++){let n=this.partsMatch(e[t],e[s],!this.preserveMultipleSlashes);if(n){e[t]=[],e[s]=n;break}}return e.filter(t=>t.length)}partsMatch(e,t,s=false){let n=0,r=0,i=[],o="";for(;n<e.length&&r<t.length;)if(e[n]===t[r])i.push(o==="b"?t[r]:e[n]),n++,r++;else if(s&&e[n]==="**"&&t[r]===e[n+1])i.push(e[n]),n++;else if(s&&t[r]==="**"&&e[n]===t[r+1])i.push(t[r]),r++;else if(e[n]==="*"&&t[r]&&(this.options.dot||!t[r].startsWith("."))&&t[r]!=="**"){if(o==="b")return false;o="a",i.push(e[n]),n++,r++;}else if(t[r]==="*"&&e[n]&&(this.options.dot||!e[n].startsWith("."))&&e[n]!=="**"){if(o==="a")return false;o="b",i.push(t[r]),n++,r++;}else return false;return e.length===t.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,s=0;for(let n=0;n<e.length&&e.charAt(n)==="!";n++)t=!t,s++;s&&(this.pattern=e.slice(s)),this.negate=t;}matchOne(e,t,s=false){let n=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),b=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),y=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),w=!y&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),C=b?3:f?0:void 0,k=w?3:y?0:void 0;if(typeof C=="number"&&typeof k=="number"){let[T,_]=[e[C],t[k]];T.toLowerCase()===_.toLowerCase()&&(t[k]=T,k>C?t=t.slice(k):C>k&&(e=e.slice(C)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var i=0,o=0,l=e.length,c=t.length;i<l&&o<c;i++,o++){this.debug("matchOne loop");var u=t[o],d=e[i];if(this.debug(t,u,d),u===false)return false;if(u===Ge){this.debug("GLOBSTAR",[t,u,d]);var p=i,h=o+1;if(h===c){for(this.debug("** at the end");i<l;i++)if(e[i]==="."||e[i]===".."||!n.dot&&e[i].charAt(0)===".")return false;return true}for(;p<l;){var g=e[p];if(this.debug(`
621
+ `),i=r.length,o=Math.min(i,s),l=r.slice(0,o);return {success:true,path:t,totalLines:i,startLine:1,endLine:o,content:ze(l,1),truncated:o<i,strategy:"full"}}buildSymbolPattern(e,t,s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r={function:`(function|async\\s+function|const|let|var)\\s+${n}\\s*[=(<]`,class:`class\\s+${n}(\\s+extends|\\s+implements|\\s*\\{|\\s*$)`,interface:`interface\\s+${n}(\\s+extends|\\s*\\{|\\s*$)`,method:s?`(${n}|${s}\\.${n})\\s*\\(`:`${n}\\s*\\(`,variable:`(const|let|var)\\s+${n}\\s*[=:]`,type:`type\\s+${n}\\s*[=<]`,enum:`enum\\s+${n}\\s*\\{`,constant:`(const|final|static\\s+final)\\s+[A-Z_]+\\s*${n}`};return t&&r[t]?r[t]:`(function|class|interface|type|enum|const|let|var|def|fn|func)\\s+${n}|${n}\\s*(=|\\()`}resolvePath(e){return te.isAbsolute(e)?e:te.resolve(this.workspacePath,e)}errorResult(e,t){return {success:false,path:e,totalLines:0,startLine:0,endLine:0,content:"",truncated:false,strategy:"chunk",error:t}}};function $a(a){return new di(a)}var dd=dg(nd());var Gn=a=>{if(typeof a!="string")throw new TypeError("invalid pattern");if(a.length>65536)throw new TypeError("pattern is too long")};var Ff={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},Un=a=>a.replace(/[[\]\\-]/g,"\\$&"),jf=a=>a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),rd=a=>a.join(""),id=(a,e)=>{let t=e;if(a.charAt(t)!=="[")throw new Error("not in a brace expression");let s=[],n=[],r=t+1,i=false,o=false,l=false,c=false,u=t,d="";e:for(;r<a.length;){let f=a.charAt(r);if((f==="!"||f==="^")&&r===t+1){c=true,r++;continue}if(f==="]"&&i&&!l){u=r+1;break}if(i=true,f==="\\"&&!l){l=true,r++;continue}if(f==="["&&!l){for(let[b,[y,w,C]]of Object.entries(Ff))if(a.startsWith(b,r)){if(d)return ["$.",false,a.length-t,true];r+=b.length,C?n.push(y):s.push(y),o=o||w;continue e}}if(l=false,d){f>d?s.push(Un(d)+"-"+Un(f)):f===d&&s.push(Un(f)),d="",r++;continue}if(a.startsWith("-]",r+1)){s.push(Un(f+"-")),r+=2;continue}if(a.startsWith("-",r+1)){d=f,r+=2;continue}s.push(Un(f)),r++;}if(u<r)return ["",false,0,false];if(!s.length&&!n.length)return ["$.",false,a.length-t,true];if(n.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let f=s[0].length===2?s[0].slice(-1):s[0];return [jf(f),false,u-t,false]}let p="["+(c?"^":"")+rd(s)+"]",h="["+(c?"":"^")+rd(n)+"]";return [s.length&&n.length?"("+p+"|"+h+")":s.length?p:h,o,u-t,true]};var St=(a,{windowsPathsNoEscape:e=false}={})=>e?a.replace(/\[([^\/\\])\]/g,"$1"):a.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var Bf=new Set(["!","?","+","*","@"]),od=a=>Bf.has(a),Gf="(?!(?:^|/)\\.\\.?(?:$|/))",mi="(?!\\.)",Uf=new Set(["[","."]),Wf=new Set(["..","."]),qf=new Set("().*{}+?[]^$\\!"),zf=a=>a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ba="[^/]",ad=Ba+"*?",ld=Ba+"+?",Vs=class a{type;#e;#t;#i=false;#n=[];#o;#w;#c;#d=false;#a;#l;#r=false;constructor(e,t,s={}){this.type=e,e&&(this.#t=true),this.#o=t,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#d&&this.#c.push(this),this.#w=this.#o?this.#o.#n.length:0;}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#n)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=true;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#n.map(e=>String(e)).join("|")+")":this.#l=this.#n.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#d)return this;this.toString(),this.#d=true;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,s=t.#o;for(;s;){for(let n=t.#w+1;!s.type&&n<s.#n.length;n++)for(let r of e.#n){if(typeof r=="string")throw new Error("string part in extglob AST??");r.copyIn(s.#n[n]);}t=s,s=t.#o;}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof a&&t.#o===this))throw new Error("invalid part: "+t);this.#n.push(t);}}toJSON(){let e=this.type===null?this.#n.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#n.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#d&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return true;if(!this.#o?.isStart())return false;if(this.#w===0)return true;let e=this.#o;for(let t=0;t<this.#w;t++){let s=e.#n[t];if(!(s instanceof a&&s.type==="!"))return false}return true}isEnd(){if(this.#e===this||this.#o?.type==="!")return true;if(!this.#o?.isEnd())return false;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#n.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this));}clone(e){let t=new a(this.type,e);for(let s of this.#n)t.copyIn(s);return t}static#y(e,t,s,n){let r=false,i=false,o=-1,l=false;if(t.type===null){let h=s,g="";for(;h<e.length;){let f=e.charAt(h++);if(r||f==="\\"){r=!r,g+=f;continue}if(i){h===o+1?(f==="^"||f==="!")&&(l=true):f==="]"&&!(h===o+2&&l)&&(i=false),g+=f;continue}else if(f==="["){i=true,o=h,l=false,g+=f;continue}if(!n.noext&&od(f)&&e.charAt(h)==="("){t.push(g),g="";let b=new a(f,t);h=a.#y(e,b,h,n),t.push(b);continue}g+=f;}return t.push(g),h}let c=s+1,u=new a(null,t),d=[],p="";for(;c<e.length;){let h=e.charAt(c++);if(r||h==="\\"){r=!r,p+=h;continue}if(i){c===o+1?(h==="^"||h==="!")&&(l=true):h==="]"&&!(c===o+2&&l)&&(i=false),p+=h;continue}else if(h==="["){i=true,o=c,l=false,p+=h;continue}if(od(h)&&e.charAt(c)==="("){u.push(p),p="";let g=new a(h,u);u.push(g),c=a.#y(e,g,c,n);continue}if(h==="|"){u.push(p),p="",d.push(u),u=new a(null,t);continue}if(h===")")return p===""&&t.#n.length===0&&(t.#r=true),u.push(p),p="",t.push(...d,u),c;p+=h;}return t.type=null,t.#t=void 0,t.#n=[e.substring(s-1)],c}static fromGlob(e,t={}){let s=new a(null,void 0,t);return a.#y(e,s,0,t),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,s,n,r]=this.toRegExpSource();if(!(n||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(r?"u":"");return Object.assign(new RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#n.map(h=>{let[g,f,b,y]=typeof h=="string"?a.#p(h,this.#t,l):h.toRegExpSource(e);return this.#t=this.#t||b,this.#i=this.#i||y,g}).join(""),u="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&Wf.has(this.#n[0]))){let g=Uf,f=t&&g.has(c.charAt(0))||c.startsWith("\\.")&&g.has(c.charAt(2))||c.startsWith("\\.\\.")&&g.has(c.charAt(4)),b=!t&&!e&&g.has(c.charAt(0));u=f?Gf:b?mi:"";}let d="";return this.isEnd()&&this.#e.#d&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,St(c),this.#t=!!this.#t,this.#i]}let s=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#m(t);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#t=void 0,[l,St(this.toString()),false,false]}let i=!s||e||t||!mi?"":this.#m(true);i===r&&(i=""),i&&(r=`(?:${r})(?:${i})*?`);let o="";if(this.type==="!"&&this.#r)o=(this.isStart()&&!t?mi:"")+ld;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?mi:"")+ad+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;o=n+r+l;}return [o,St(r),this.#t=!!this.#t,this.#i]}#m(e){return this.#n.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[s,n,r,i]=t.toRegExpSource(e);return this.#i=this.#i||i,s}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#p(e,t,s=false){let n=false,r="",i=false;for(let o=0;o<e.length;o++){let l=e.charAt(o);if(n){n=false,r+=(qf.has(l)?"\\":"")+l;continue}if(l==="\\"){o===e.length-1?r+="\\\\":n=true;continue}if(l==="["){let[c,u,d,p]=id(e,o);if(d){r+=c,i=i||u,o+=d-1,t=t||p;continue}}if(l==="*"){s&&e==="*"?r+=ld:r+=ad,t=true;continue}if(l==="?"){r+=Ba,t=true;continue}r+=zf(l);}return [r,St(e),!!t,i]}};var Ys=(a,{windowsPathsNoEscape:e=false}={})=>e?a.replace(/[?*()[\]]/g,"[$&]"):a.replace(/[?*()[\]\\]/g,"\\$&");var Xe=(a,e,t={})=>(Gn(e),!t.nocomment&&e.charAt(0)==="#"?false:new ct(e,t).match(a)),Hf=/^\*+([^+@!?\*\[\(]*)$/,Jf=a=>e=>!e.startsWith(".")&&e.endsWith(a),Kf=a=>e=>e.endsWith(a),Vf=a=>(a=a.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(a)),Yf=a=>(a=a.toLowerCase(),e=>e.toLowerCase().endsWith(a)),Xf=/^\*+\.\*+$/,Qf=a=>!a.startsWith(".")&&a.includes("."),Zf=a=>a!=="."&&a!==".."&&a.includes("."),ey=/^\.\*+$/,ty=a=>a!=="."&&a!==".."&&a.startsWith("."),sy=/^\*+$/,ny=a=>a.length!==0&&!a.startsWith("."),ry=a=>a.length!==0&&a!=="."&&a!=="..",iy=/^\?+([^+@!?\*\[\(]*)?$/,oy=([a,e=""])=>{let t=pd([a]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},ay=([a,e=""])=>{let t=md([a]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},ly=([a,e=""])=>{let t=md([a]);return e?s=>t(s)&&s.endsWith(e):t},cy=([a,e=""])=>{let t=pd([a]);return e?s=>t(s)&&s.endsWith(e):t},pd=([a])=>{let e=a.length;return t=>t.length===e&&!t.startsWith(".")},md=([a])=>{let e=a.length;return t=>t.length===e&&t!=="."&&t!==".."},gd=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",cd={win32:{sep:"\\"},posix:{sep:"/"}},uy=gd==="win32"?cd.win32.sep:cd.posix.sep;Xe.sep=uy;var Ge=Symbol("globstar **");Xe.GLOBSTAR=Ge;var dy="[^/]",py=dy+"*?",my="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",gy="(?:(?!(?:\\/|^)\\.).)*?",hy=(a,e={})=>t=>Xe(t,a,e);Xe.filter=hy;var pt=(a,e={})=>Object.assign({},a,e),fy=a=>{if(!a||typeof a!="object"||!Object.keys(a).length)return Xe;let e=Xe;return Object.assign((s,n,r={})=>e(s,n,pt(a,r)),{Minimatch:class extends e.Minimatch{constructor(n,r={}){super(n,pt(a,r));}static defaults(n){return e.defaults(pt(a,n)).Minimatch}},AST:class extends e.AST{constructor(n,r,i={}){super(n,r,pt(a,i));}static fromGlob(n,r={}){return e.AST.fromGlob(n,pt(a,r))}},unescape:(s,n={})=>e.unescape(s,pt(a,n)),escape:(s,n={})=>e.escape(s,pt(a,n)),filter:(s,n={})=>e.filter(s,pt(a,n)),defaults:s=>e.defaults(pt(a,s)),makeRe:(s,n={})=>e.makeRe(s,pt(a,n)),braceExpand:(s,n={})=>e.braceExpand(s,pt(a,n)),match:(s,n,r={})=>e.match(s,n,pt(a,r)),sep:e.sep,GLOBSTAR:Ge})};Xe.defaults=fy;var hd=(a,e={})=>(Gn(a),e.nobrace||!/\{(?:(?!\{).)*\}/.test(a)?[a]:(0, dd.default)(a));Xe.braceExpand=hd;var yy=(a,e={})=>new ct(a,e).makeRe();Xe.makeRe=yy;var by=(a,e,t={})=>{let s=new ct(e,t);return a=a.filter(n=>s.match(n)),s.options.nonull&&!a.length&&a.push(e),a};Xe.match=by;var ud=/[?*]|[+@!]\(.*?\)|\[|\]/,vy=a=>a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ct=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Gn(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||gd,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let n=this.globParts.map((r,i,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=r[0]===""&&r[1]===""&&(r[2]==="?"||!ud.test(r[2]))&&!ud.test(r[3]),c=/^[a-z]:/i.test(r[0]);if(l)return [...r.slice(0,4),...r.slice(4).map(u=>this.parse(u))];if(c)return [r[0],...r.slice(1).map(u=>this.parse(u))]}return r.map(l=>this.parse(l))});if(this.debug(this.pattern,n),this.set=n.filter(r=>r.indexOf(false)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){let i=this.set[r];i[0]===""&&i[1]===""&&this.globParts[r][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let s=0;s<e.length;s++)for(let n=0;n<e[s].length;n++)e[s][n]==="**"&&(e[s][n]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let s=-1;for(;(s=t.indexOf("**",s+1))!==-1;){let n=s;for(;t[n+1]==="**";)n++;n!==s&&t.splice(s,n-s);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((s,n)=>{let r=s[s.length-1];return n==="**"&&r==="**"?s:n===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(n),s)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===""&&e[0]===""||(r==="."||r==="")&&(t=true,e.splice(n,1),n--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let s=0;for(;(s=e.indexOf("..",s+1))!==-1;){let n=e[s-1];n&&n!=="."&&n!==".."&&n!=="**"&&(t=true,e.splice(s-1,2),s-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let s of e){let n=-1;for(;(n=s.indexOf("**",n+1))!==-1;){let i=n;for(;s[i+1]==="**";)i++;i>n&&s.splice(n+1,i-n);let o=s[n+1],l=s[n+2],c=s[n+3];if(o!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=true,s.splice(n,1);let u=s.slice(0);u[n]="**",e.push(u),n--;}if(!this.preserveMultipleSlashes){for(let i=1;i<s.length-1;i++){let o=s[i];i===1&&o===""&&s[0]===""||(o==="."||o==="")&&(t=true,s.splice(i,1),i--);}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(t=true,s.pop());}let r=0;for(;(r=s.indexOf("..",r+1))!==-1;){let i=s[r-1];if(i&&i!=="."&&i!==".."&&i!=="**"){t=true;let l=r===1&&s[r+1]==="**"?["."]:[];s.splice(r-1,2,...l),s.length===0&&s.push(""),r-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++){let n=this.partsMatch(e[t],e[s],!this.preserveMultipleSlashes);if(n){e[t]=[],e[s]=n;break}}return e.filter(t=>t.length)}partsMatch(e,t,s=false){let n=0,r=0,i=[],o="";for(;n<e.length&&r<t.length;)if(e[n]===t[r])i.push(o==="b"?t[r]:e[n]),n++,r++;else if(s&&e[n]==="**"&&t[r]===e[n+1])i.push(e[n]),n++;else if(s&&t[r]==="**"&&e[n]===t[r+1])i.push(t[r]),r++;else if(e[n]==="*"&&t[r]&&(this.options.dot||!t[r].startsWith("."))&&t[r]!=="**"){if(o==="b")return false;o="a",i.push(e[n]),n++,r++;}else if(t[r]==="*"&&e[n]&&(this.options.dot||!e[n].startsWith("."))&&e[n]!=="**"){if(o==="a")return false;o="b",i.push(t[r]),n++,r++;}else return false;return e.length===t.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,s=0;for(let n=0;n<e.length&&e.charAt(n)==="!";n++)t=!t,s++;s&&(this.pattern=e.slice(s)),this.negate=t;}matchOne(e,t,s=false){let n=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),b=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),y=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),w=!y&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),C=b?3:f?0:void 0,k=w?3:y?0:void 0;if(typeof C=="number"&&typeof k=="number"){let[T,_]=[e[C],t[k]];T.toLowerCase()===_.toLowerCase()&&(t[k]=T,k>C?t=t.slice(k):C>k&&(e=e.slice(C)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var i=0,o=0,l=e.length,c=t.length;i<l&&o<c;i++,o++){this.debug("matchOne loop");var u=t[o],d=e[i];if(this.debug(t,u,d),u===false)return false;if(u===Ge){this.debug("GLOBSTAR",[t,u,d]);var p=i,h=o+1;if(h===c){for(this.debug("** at the end");i<l;i++)if(e[i]==="."||e[i]===".."||!n.dot&&e[i].charAt(0)===".")return false;return true}for(;p<l;){var g=e[p];if(this.debug(`
622
622
  globstar while`,e,p,t,h,g),this.matchOne(e.slice(p),t.slice(h),s))return this.debug("globstar found match!",p,l,g),true;if(g==="."||g===".."||!n.dot&&g.charAt(0)==="."){this.debug("dot detected!",e,p,t,h);break}this.debug("globstar swallow a segment, and continue"),p++;}return !!(s&&(this.debug(`
623
- >>> no match, partial?`,e,p,t,h),p===l))}let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return false}if(i===l&&o===c)return true;if(i===l)return s;if(o===c)return i===l-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return hd(this.pattern,this.options)}parse(e){Gn(e);let t=this.options;if(e==="**")return Ge;if(e==="")return "";let s,n=null;(s=e.match(ty))?n=t.dot?ny:sy:(s=e.match(zf))?n=(t.nocase?t.dot?Vf:Kf:t.dot?Jf:Hf)(s[1]):(s=e.match(ry))?n=(t.nocase?t.dot?oy:iy:t.dot?ay:ly)(s):(s=e.match(Yf))?n=t.dot?Qf:Xf:(s=e.match(Zf))&&(n=ey);let r=Vs.fromGlob(e,this.options).toMMPattern();return n&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:n}),r}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,s=t.noglobstar?dy:t.dot?py:my,n=new Set(t.nocase?["i"]:[]),r=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))n.add(d);return typeof u=="string"?by(u):u===Ge?Ge:u._src});return c.forEach((u,d)=>{let p=c[d+1],h=c[d-1];u!==Ge||h===Ge||(h===void 0?p!==void 0&&p!==Ge?c[d+1]="(?:\\/|"+s+"\\/)?"+p:c[d]=s:p===void 0?c[d-1]=h+"(?:\\/|"+s+")?":p!==Ge&&(c[d-1]=h+"(?:\\/|\\/"+s+"\\/)"+p,c[d+1]=Ge));}),c.filter(u=>u!==Ge).join("/")}).join("|"),[i,o]=e.length>1?["(?:",")"]:["",""];r="^"+i+r+o+"$",this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...n].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let s=this.options;this.isWindows&&(e=e.split("\\").join("/"));let n=this.slashSplit(e);this.debug(this.pattern,"split",n);let r=this.set;this.debug(this.pattern,"set",r);let i=n[n.length-1];if(!i)for(let o=n.length-2;!i&&o>=0;o--)i=n[o];for(let o=0;o<r.length;o++){let l=r[o],c=n;if(s.matchBase&&l.length===1&&(c=[i]),this.matchOne(c,l,t))return s.flipNegate?true:!this.negate}return s.flipNegate?false:this.negate}static defaults(e){return Xe.defaults(e).Minimatch}};Xe.AST=Vs;Xe.Minimatch=ct;Xe.escape=Ys;Xe.unescape=St;var Xs=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,yd=new Set,Ga=typeof process=="object"&&process?process:{},bd=(a,e,t,s)=>{typeof Ga.emitWarning=="function"?Ga.emitWarning(a,e,t,s):console.error(`[${t}] ${e}: ${a}`);},gi=globalThis.AbortController,fd=globalThis.AbortSignal;if(typeof gi>"u"){fd=class{onabort;_onabort=[];reason;aborted=false;addEventListener(s,n){this._onabort.push(n);}},gi=class{constructor(){e();}signal=new fd;abort(s){if(!this.signal.aborted){this.signal.reason=s,this.signal.aborted=true;for(let n of this.signal._onabort)n(s);this.signal.onabort?.(s);}}};let a=Ga.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{a&&(a=false,bd("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e));};}var vy=a=>!yd.has(a);var es=a=>a&&a===Math.floor(a)&&a>0&&isFinite(a),vd=a=>es(a)?a<=Math.pow(2,8)?Uint8Array:a<=Math.pow(2,16)?Uint16Array:a<=Math.pow(2,32)?Uint32Array:a<=Number.MAX_SAFE_INTEGER?Qs:null:null,Qs=class extends Array{constructor(e){super(e),this.fill(0);}},Ua=class a{heap;length;static#e=false;static create(e){let t=vd(e);if(!t)return [];a.#e=true;let s=new a(e,t);return a.#e=false,s}constructor(e,t){if(!a.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0;}push(e){this.heap[this.length++]=e;}pop(){return this.heap[--this.length]}},Wn=class a{#e;#t;#i;#n;#o;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#d;#a;#l;#r;#f;#y;#m;#p;#S;#h;#x;#T;#v;#C;#k;#g;static unsafeExposeInternals(e){return {starts:e.#T,ttls:e.#v,sizes:e.#x,keyMap:e.#a,keyList:e.#l,valList:e.#r,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#p},free:e.#S,isBackgroundFetch:t=>e.#u(t),backgroundFetch:(t,s,n,r)=>e.#F(t,s,n,r),moveToTail:t=>e.#B(t),indexes:t=>e.#R(t),rindexes:t=>e.#A(t),isStale:t=>e.#b(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#d}get size(){return this.#c}get fetchMethod(){return this.#o}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#n}constructor(e){let{max:t=0,ttl:s,ttlResolution:n=1,ttlAutopurge:r,updateAgeOnGet:i,updateAgeOnHas:o,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:p,maxSize:h=0,maxEntrySize:g=0,sizeCalculation:f,fetchMethod:b,memoMethod:y,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:C,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:T,ignoreFetchAbort:_}=e;if(t!==0&&!es(t))throw new TypeError("max option must be a nonnegative integer");let M=t?vd(t):Array;if(!M)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=h,this.maxEntrySize=g||this.#t,this.sizeCalculation=f,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=y,b!==void 0&&typeof b!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#o=b,this.#k=!!b,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#r=new Array(t).fill(void 0),this.#f=new M(t),this.#y=new M(t),this.#m=0,this.#p=0,this.#S=Ua.create(t),this.#c=0,this.#d=0,typeof c=="function"&&(this.#i=c),typeof u=="function"?(this.#n=u,this.#h=[]):(this.#n=void 0,this.#h=void 0),this.#C=!!this.#i,this.#g=!!this.#n,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!_,this.maxEntrySize!==0){if(this.#t!==0&&!es(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!es(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#I();}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!C,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!o,this.ttlResolution=es(n)||n===0?n:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!es(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#E();}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let F="LRU_CACHE_UNBOUNDED";vy(F)&&(yd.add(F),bd("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",F,a));}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#E(){let e=new Qs(this.#e),t=new Qs(this.#e);this.#v=e,this.#T=t,this.#P=(r,i,o=Xs.now())=>{if(t[r]=i!==0?o:0,e[r]=i,i!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(r)&&this.#M(this.#l[r],"expire");},i+1);l.unref&&l.unref();}},this.#_=r=>{t[r]=e[r]!==0?Xs.now():0;},this.#s=(r,i)=>{if(e[i]){let o=e[i],l=t[i];if(!o||!l)return;r.ttl=o,r.start=l,r.now=s||n();let c=r.now-l;r.remainingTTL=o-c;}};let s=0,n=()=>{let r=Xs.now();if(this.ttlResolution>0){s=r;let i=setTimeout(()=>s=0,this.ttlResolution);i.unref&&i.unref();}return r};this.getRemainingTTL=r=>{let i=this.#a.get(r);if(i===void 0)return 0;let o=e[i],l=t[i];if(!o||!l)return 1/0;let c=(s||n())-l;return o-c},this.#b=r=>{let i=t[r],o=e[r];return !!o&&!!i&&(s||n())-i>o};}#_=()=>{};#s=()=>{};#P=()=>{};#b=()=>false;#I(){let e=new Qs(this.#e);this.#d=0,this.#x=e,this.#D=t=>{this.#d-=e[t],e[t]=0;},this.#O=(t,s,n,r)=>{if(this.#u(s))return 0;if(!es(n))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(n=r(s,t),!es(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return n},this.#L=(t,s,n)=>{if(e[t]=s,this.#t){let r=this.#t-e[t];for(;this.#d>r;)this.#$(true);}this.#d+=e[t],n&&(n.entrySize=s,n.totalCalculatedSize=this.#d);};}#D=e=>{};#L=(e,t,s)=>{};#O=(e,t,s,n)=>{if(s||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;!(!this.#N(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t];}*#A({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#N(t)||((e||!this.#b(t))&&(yield t),t===this.#p));)t=this.#f[t];}#N(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*rentries(){for(let e of this.#A())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*keys(){for(let e of this.#R()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*rkeys(){for(let e of this.#A()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*values(){for(let e of this.#R())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}*rvalues(){for(let e of this.#A())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let s of this.#R()){let n=this.#r[s],r=this.#u(n)?n.__staleWhileFetching:n;if(r!==void 0&&e(r,this.#l[s],this))return this.get(this.#l[s],t)}}forEach(e,t=this){for(let s of this.#R()){let n=this.#r[s],r=this.#u(n)?n.__staleWhileFetching:n;r!==void 0&&e.call(t,r,this.#l[s],this);}}rforEach(e,t=this){for(let s of this.#A()){let n=this.#r[s],r=this.#u(n)?n.__staleWhileFetching:n;r!==void 0&&e.call(t,r,this.#l[s],this);}}purgeStale(){let e=false;for(let t of this.#A({allowStale:true}))this.#b(t)&&(this.#M(this.#l[t],"expire"),e=true);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let s=this.#r[t],n=this.#u(s)?s.__staleWhileFetching:s;if(n===void 0)return;let r={value:n};if(this.#v&&this.#T){let i=this.#v[t],o=this.#T[t];if(i&&o){let l=i-(Xs.now()-o);r.ttl=l,r.start=Date.now();}}return this.#x&&(r.size=this.#x[t]),r}dump(){let e=[];for(let t of this.#R({allowStale:true})){let s=this.#l[t],n=this.#r[t],r=this.#u(n)?n.__staleWhileFetching:n;if(r===void 0||s===void 0)continue;let i={value:r};if(this.#v&&this.#T){i.ttl=this.#v[t];let o=Xs.now()-this.#T[t];i.start=Math.floor(Date.now()-o);}this.#x&&(i.size=this.#x[t]),e.unshift([s,i]);}return e}load(e){this.clear();for(let[t,s]of e){if(s.start){let n=Date.now()-s.start;s.start=Xs.now()-n;}this.set(t,s.value,s);}}set(e,t,s={}){if(t===void 0)return this.delete(e),this;let{ttl:n=this.ttl,start:r,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#O(e,t,s.size||0,o);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),this.#M(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#p:this.#S.length!==0?this.#S.pop():this.#c===this.#e?this.#$(false):this.#c,this.#l[d]=e,this.#r[d]=t,this.#a.set(e,d),this.#f[this.#p]=d,this.#y[d]=this.#p,this.#p=d,this.#c++,this.#L(d,u,l),l&&(l.set="add"),c=false;else {this.#B(d);let p=this.#r[d];if(t!==p){if(this.#k&&this.#u(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=p;h!==void 0&&!i&&(this.#C&&this.#i?.(h,e,"set"),this.#g&&this.#h?.push([h,e,"set"]));}else i||(this.#C&&this.#i?.(p,e,"set"),this.#g&&this.#h?.push([p,e,"set"]));if(this.#D(d),this.#L(d,u,l),this.#r[d]=t,l){l.set="replace";let h=p&&this.#u(p)?p.__staleWhileFetching:p;h!==void 0&&(l.oldValue=h);}}else l&&(l.set="update");}if(n!==0&&!this.#v&&this.#E(),this.#v&&(c||this.#P(d,n,r),l&&this.#s(l,d)),!i&&this.#g&&this.#h){let p=this.#h,h;for(;h=p?.shift();)this.#n?.(...h);}return this}pop(){try{for(;this.#c;){let e=this.#r[this.#m];if(this.#$(!0),this.#u(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#g&&this.#h){let e=this.#h,t;for(;t=e?.shift();)this.#n?.(...t);}}}#$(e){let t=this.#m,s=this.#l[t],n=this.#r[t];return this.#k&&this.#u(n)?n.__abortController.abort(new Error("evicted")):(this.#C||this.#g)&&(this.#C&&this.#i?.(n,s,"evict"),this.#g&&this.#h?.push([n,s,"evict"])),this.#D(t),e&&(this.#l[t]=void 0,this.#r[t]=void 0,this.#S.push(t)),this.#c===1?(this.#m=this.#p=0,this.#S.length=0):this.#m=this.#f[t],this.#a.delete(s),this.#c--,t}has(e,t={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:n}=t,r=this.#a.get(e);if(r!==void 0){let i=this.#r[r];if(this.#u(i)&&i.__staleWhileFetching===void 0)return false;if(this.#b(r))n&&(n.has="stale",this.#s(n,r));else return s&&this.#_(r),n&&(n.has="hit",this.#s(n,r)),true}else n&&(n.has="miss");return false}peek(e,t={}){let{allowStale:s=this.allowStale}=t,n=this.#a.get(e);if(n===void 0||!s&&this.#b(n))return;let r=this.#r[n];return this.#u(r)?r.__staleWhileFetching:r}#F(e,t,s,n){let r=t===void 0?void 0:this.#r[t];if(this.#u(r))return r;let i=new gi,{signal:o}=s;o?.addEventListener("abort",()=>i.abort(o.reason),{signal:i.signal});let l={signal:i.signal,options:s,context:n},c=(f,b=false)=>{let{aborted:y}=i.signal,w=s.ignoreFetchAbort&&f!==void 0;if(s.status&&(y&&!b?(s.status.fetchAborted=true,s.status.fetchError=i.signal.reason,w&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),y&&!w&&!b)return d(i.signal.reason);let C=h;return this.#r[t]===h&&(f===void 0?C.__staleWhileFetching?this.#r[t]=C.__staleWhileFetching:this.#M(e,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(e,f,l.options))),f},u=f=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=f),d(f)),d=f=>{let{aborted:b}=i.signal,y=b&&s.allowStaleOnFetchAbort,w=y||s.allowStaleOnFetchRejection,C=w||s.noDeleteOnFetchRejection,k=h;if(this.#r[t]===h&&(!C||k.__staleWhileFetching===void 0?this.#M(e,"fetch"):y||(this.#r[t]=k.__staleWhileFetching)),w)return s.status&&k.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),k.__staleWhileFetching;if(k.__returned===k)throw f},p=(f,b)=>{let y=this.#o?.(e,r,l);y&&y instanceof Promise&&y.then(w=>f(w===void 0?void 0:w),b),i.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(f(void 0),s.allowStaleOnFetchAbort&&(f=w=>c(w,true)));});};s.status&&(s.status.fetchDispatched=true);let h=new Promise(p).then(c,u),g=Object.assign(h,{__abortController:i,__staleWhileFetching:r,__returned:void 0});return t===void 0?(this.set(e,g,{...l.options,status:void 0}),t=this.#a.get(e)):this.#r[t]=g,g}#u(e){if(!this.#k)return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof gi}async fetch(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=false,status:y,signal:w}=t;if(!this.#k)return y&&(y.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:r,status:y});let C={allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:r,ttl:i,noDisposeOnSet:o,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:g,ignoreFetchAbort:h,status:y,signal:w},k=this.#a.get(e);if(k===void 0){y&&(y.fetch="miss");let T=this.#F(e,k,C,f);return T.__returned=T}else {let T=this.#r[k];if(this.#u(T)){let R=s&&T.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",R&&(y.returnedStale=true)),R?T.__staleWhileFetching:T.__returned=T}let _=this.#b(k);if(!b&&!_)return y&&(y.fetch="hit"),this.#B(k),n&&this.#_(k),y&&this.#s(y,k),T;let M=this.#F(e,k,C,f),x=M.__staleWhileFetching!==void 0&&s;return y&&(y.fetch=_?"stale":"refresh",x&&_&&(y.returnedStale=true)),x?M.__staleWhileFetching:M.__returned=M}}async forceFetch(e,t={}){let s=await this.fetch(e,t);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,t={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:n,forceRefresh:r,...i}=t,o=this.get(e,i);if(!r&&o!==void 0)return o;let l=s(e,o,{options:i,context:n});return this.set(e,l,i),l}get(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:i}=t,o=this.#a.get(e);if(o!==void 0){let l=this.#r[o],c=this.#u(l);return i&&this.#s(i,o),this.#b(o)?(i&&(i.get="stale"),c?(i&&s&&l.__staleWhileFetching!==void 0&&(i.returnedStale=true),s?l.__staleWhileFetching:void 0):(r||this.#M(e,"expire"),i&&s&&(i.returnedStale=true),s?l:void 0)):(i&&(i.get="hit"),c?l.__staleWhileFetching:(this.#B(o),n&&this.#_(o),l))}else i&&(i.get="miss");}#j(e,t){this.#y[t]=e,this.#f[e]=t;}#B(e){e!==this.#p&&(e===this.#m?this.#m=this.#f[e]:this.#j(this.#y[e],this.#f[e]),this.#j(this.#p,e),this.#p=e);}delete(e){return this.#M(e,"delete")}#M(e,t){let s=false;if(this.#c!==0){let n=this.#a.get(e);if(n!==void 0)if(s=true,this.#c===1)this.#G(t);else {this.#D(n);let r=this.#r[n];if(this.#u(r)?r.__abortController.abort(new Error("deleted")):(this.#C||this.#g)&&(this.#C&&this.#i?.(r,e,t),this.#g&&this.#h?.push([r,e,t])),this.#a.delete(e),this.#l[n]=void 0,this.#r[n]=void 0,n===this.#p)this.#p=this.#y[n];else if(n===this.#m)this.#m=this.#f[n];else {let i=this.#y[n];this.#f[i]=this.#f[n];let o=this.#f[n];this.#y[o]=this.#y[n];}this.#c--,this.#S.push(n);}}if(this.#g&&this.#h?.length){let n=this.#h,r;for(;r=n?.shift();)this.#n?.(...r);}return s}clear(){return this.#G("delete")}#G(e){for(let t of this.#A({allowStale:true})){let s=this.#r[t];if(this.#u(s))s.__abortController.abort(new Error("deleted"));else {let n=this.#l[t];this.#C&&this.#i?.(s,n,e),this.#g&&this.#h?.push([s,n,e]);}}if(this.#a.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#v&&this.#T&&(this.#v.fill(0),this.#T.fill(0)),this.#x&&this.#x.fill(0),this.#m=0,this.#p=0,this.#S.length=0,this.#d=0,this.#c=0,this.#g&&this.#h){let t=this.#h,s;for(;s=t?.shift();)this.#n?.(...s);}}};var wd=typeof process=="object"&&process?process:{stdout:null,stderr:null},Cy=a=>!!a&&typeof a=="object"&&(a instanceof ss||a instanceof xd||ky(a)||Sy(a)),ky=a=>!!a&&typeof a=="object"&&a instanceof EventEmitter&&typeof a.pipe=="function"&&a.pipe!==xd.Writable.prototype.pipe,Sy=a=>!!a&&typeof a=="object"&&a instanceof EventEmitter&&typeof a.write=="function"&&typeof a.end=="function",Ut=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),ts=Symbol("emittedEnd"),hi=Symbol("emittingEnd"),qn=Symbol("emittedError"),fi=Symbol("closed"),Cd=Symbol("read"),yi=Symbol("flush"),kd=Symbol("flushChunk"),xt=Symbol("encoding"),Zs=Symbol("decoder"),Ne=Symbol("flowing"),zn=Symbol("paused"),en=Symbol("resume"),$e=Symbol("buffer"),Qe=Symbol("pipes"),Fe=Symbol("bufferLength"),Wa=Symbol("bufferPush"),bi=Symbol("bufferShift"),He=Symbol("objectMode"),Ee=Symbol("destroyed"),qa=Symbol("error"),za=Symbol("emitData"),Sd=Symbol("emitEnd"),Ha=Symbol("emitEnd2"),Mt=Symbol("async"),Ja=Symbol("abort"),vi=Symbol("aborted"),Hn=Symbol("signal"),Cs=Symbol("dataListeners"),ut=Symbol("discarded"),Jn=a=>Promise.resolve().then(a),xy=a=>a(),Ty=a=>a==="end"||a==="finish"||a==="prefinish",_y=a=>a instanceof ArrayBuffer||!!a&&typeof a=="object"&&a.constructor&&a.constructor.name==="ArrayBuffer"&&a.byteLength>=0,Ry=a=>!Buffer.isBuffer(a)&&ArrayBuffer.isView(a),wi=class{src;dest;opts;ondrain;constructor(e,t,s){this.src=e,this.dest=t,this.opts=s,this.ondrain=()=>e[en](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Ka=class extends wi{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,s){super(e,t,s),this.proxyErrors=n=>t.emit("error",n),e.on("error",this.proxyErrors);}},Ay=a=>!!a.objectMode,Ey=a=>!a.objectMode&&!!a.encoding&&a.encoding!=="buffer",ss=class extends EventEmitter{[Ne]=false;[zn]=false;[Qe]=[];[$e]=[];[He];[xt];[Mt];[Zs];[Ut]=false;[ts]=false;[hi]=false;[fi]=false;[qn]=null;[Fe]=0;[Ee]=false;[Hn];[vi]=false;[Cs]=0;[ut]=false;writable=true;readable=true;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Ay(t)?(this[He]=true,this[xt]=null):Ey(t)?(this[xt]=t.encoding,this[He]=false):(this[He]=false,this[xt]=null),this[Mt]=!!t.async,this[Zs]=this[xt]?new StringDecoder(this[xt]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[$e]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:s}=t;s&&(this[Hn]=s,s.aborted?this[Ja]():s.addEventListener("abort",()=>this[Ja]()));}get bufferLength(){return this[Fe]}get encoding(){return this[xt]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[He]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Mt]}set async(e){this[Mt]=this[Mt]||!!e;}[Ja](){this[vi]=true,this.emit("abort",this[Hn]?.reason),this.destroy(this[Hn]?.reason);}get aborted(){return this[vi]}set aborted(e){}write(e,t,s){if(this[vi])return false;if(this[Ut])throw new Error("write after end");if(this[Ee])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(s=t,t="utf8"),t||(t="utf8");let n=this[Mt]?Jn:xy;if(!this[He]&&!Buffer.isBuffer(e)){if(Ry(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(_y(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[He]?(this[Ne]&&this[Fe]!==0&&this[yi](true),this[Ne]?this.emit("data",e):this[Wa](e),this[Fe]!==0&&this.emit("readable"),s&&n(s),this[Ne]):e.length?(typeof e=="string"&&!(t===this[xt]&&!this[Zs]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[xt]&&(e=this[Zs].write(e)),this[Ne]&&this[Fe]!==0&&this[yi](true),this[Ne]?this.emit("data",e):this[Wa](e),this[Fe]!==0&&this.emit("readable"),s&&n(s),this[Ne]):(this[Fe]!==0&&this.emit("readable"),s&&n(s),this[Ne])}read(e){if(this[Ee])return null;if(this[ut]=false,this[Fe]===0||e===0||e&&e>this[Fe])return this[Wt](),null;this[He]&&(e=null),this[$e].length>1&&!this[He]&&(this[$e]=[this[xt]?this[$e].join(""):Buffer.concat(this[$e],this[Fe])]);let t=this[Cd](e||null,this[$e][0]);return this[Wt](),t}[Cd](e,t){if(this[He])this[bi]();else {let s=t;e===s.length||e===null?this[bi]():typeof s=="string"?(this[$e][0]=s.slice(e),t=s.slice(0,e),this[Fe]-=e):(this[$e][0]=s.subarray(e),t=s.subarray(0,e),this[Fe]-=e);}return this.emit("data",t),!this[$e].length&&!this[Ut]&&this.emit("drain"),t}end(e,t,s){return typeof e=="function"&&(s=e,e=void 0),typeof t=="function"&&(s=t,t="utf8"),e!==void 0&&this.write(e,t),s&&this.once("end",s),this[Ut]=true,this.writable=false,(this[Ne]||!this[zn])&&this[Wt](),this}[en](){this[Ee]||(!this[Cs]&&!this[Qe].length&&(this[ut]=true),this[zn]=false,this[Ne]=true,this.emit("resume"),this[$e].length?this[yi]():this[Ut]?this[Wt]():this.emit("drain"));}resume(){return this[en]()}pause(){this[Ne]=false,this[zn]=true,this[ut]=false;}get destroyed(){return this[Ee]}get flowing(){return this[Ne]}get paused(){return this[zn]}[Wa](e){this[He]?this[Fe]+=1:this[Fe]+=e.length,this[$e].push(e);}[bi](){return this[He]?this[Fe]-=1:this[Fe]-=this[$e][0].length,this[$e].shift()}[yi](e=false){do;while(this[kd](this[bi]())&&this[$e].length);!e&&!this[$e].length&&!this[Ut]&&this.emit("drain");}[kd](e){return this.emit("data",e),this[Ne]}pipe(e,t){if(this[Ee])return e;this[ut]=false;let s=this[ts];return t=t||{},e===wd.stdout||e===wd.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,s?t.end&&e.end():(this[Qe].push(t.proxyErrors?new Ka(this,e,t):new wi(this,e,t)),this[Mt]?Jn(()=>this[en]()):this[en]()),e}unpipe(e){let t=this[Qe].find(s=>s.dest===e);t&&(this[Qe].length===1?(this[Ne]&&this[Cs]===0&&(this[Ne]=false),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let s=super.on(e,t);if(e==="data")this[ut]=false,this[Cs]++,!this[Qe].length&&!this[Ne]&&this[en]();else if(e==="readable"&&this[Fe]!==0)super.emit("readable");else if(Ty(e)&&this[ts])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[qn]){let n=t;this[Mt]?Jn(()=>n.call(this,this[qn])):n.call(this,this[qn]);}return s}removeListener(e,t){return this.off(e,t)}off(e,t){let s=super.off(e,t);return e==="data"&&(this[Cs]=this.listeners("data").length,this[Cs]===0&&!this[ut]&&!this[Qe].length&&(this[Ne]=false)),s}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[Cs]=0,!this[ut]&&!this[Qe].length&&(this[Ne]=false)),t}get emittedEnd(){return this[ts]}[Wt](){!this[hi]&&!this[ts]&&!this[Ee]&&this[$e].length===0&&this[Ut]&&(this[hi]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[fi]&&this.emit("close"),this[hi]=false);}emit(e,...t){let s=t[0];if(e!=="error"&&e!=="close"&&e!==Ee&&this[Ee])return false;if(e==="data")return !this[He]&&!s?false:this[Mt]?(Jn(()=>this[za](s)),true):this[za](s);if(e==="end")return this[Sd]();if(e==="close"){if(this[fi]=true,!this[ts]&&!this[Ee])return false;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(e==="error"){this[qn]=s,super.emit(qa,s);let r=!this[Hn]||this.listeners("error").length?super.emit("error",s):false;return this[Wt](),r}else if(e==="resume"){let r=super.emit("resume");return this[Wt](),r}else if(e==="finish"||e==="prefinish"){let r=super.emit(e);return this.removeAllListeners(e),r}let n=super.emit(e,...t);return this[Wt](),n}[za](e){for(let s of this[Qe])s.dest.write(e)===false&&this.pause();let t=this[ut]?false:super.emit("data",e);return this[Wt](),t}[Sd](){return this[ts]?false:(this[ts]=true,this.readable=false,this[Mt]?(Jn(()=>this[Ha]()),true):this[Ha]())}[Ha](){if(this[Zs]){let t=this[Zs].end();if(t){for(let s of this[Qe])s.dest.write(t);this[ut]||super.emit("data",t);}}for(let t of this[Qe])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[He]||(e.dataLength=0);let t=this.promise();return this.on("data",s=>{e.push(s),this[He]||(e.dataLength+=s.length);}),await t,e}async concat(){if(this[He])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[xt]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Ee,()=>t(new Error("stream destroyed"))),this.on("error",s=>t(s)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[ut]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:false,value:n});if(this[Ut])return t();let r,i,o=d=>{this.off("data",l),this.off("end",c),this.off(Ee,u),t(),i(d);},l=d=>{this.off("error",o),this.off("end",c),this.off(Ee,u),this.pause(),r({value:d,done:!!this[Ut]});},c=()=>{this.off("error",o),this.off("data",l),this.off(Ee,u),t(),r({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,p)=>{i=p,r=d,this.once(Ee,u),this.once("error",o),this.once("end",c),this.once("data",l);})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[ut]=false;let e=false,t=()=>(this.pause(),this.off(qa,t),this.off(Ee,t),this.off("end",t),e=true,{done:true,value:void 0}),s=()=>{if(e)return t();let n=this.read();return n===null?t():{done:false,value:n}};return this.once("end",t),this.once(qa,t),this.once(Ee,t),{next:s,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Ee])return e?this.emit("error",e):this.emit(Ee),this;this[Ee]=true,this[ut]=true,this[$e].length=0,this[Fe]=0;let t=this;return typeof t.close=="function"&&!this[fi]&&t.close(),e?this.emit("error",e):this.emit(Ee),this}static get isStream(){return Cy}};var Fy=realpathSync.native,Vn={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Fy,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Ed=a=>!a||a===Vn||a===Me?Vn:{...Vn,...a,promises:{...Vn.promises,...a.promises||{}}},Id=/^\\\\\?\\([a-z]:)\\?$/i,Wy=a=>a.replace(/\//g,"\\").replace(Id,"$1\\"),qy=/[\\\/]/,gt=0,Md=1,Pd=2,Pt=4,Dd=6,Ld=8,ks=10,Od=12,mt=15,Kn=~mt,Ya=16,Td=32,Yn=64,Tt=128,Ci=256,Si=512,_d=Yn|Tt|Si,zy=1023,Xa=a=>a.isFile()?Ld:a.isDirectory()?Pt:a.isSymbolicLink()?ks:a.isCharacterDevice()?Pd:a.isBlockDevice()?Dd:a.isSocket()?Od:a.isFIFO()?Md:gt,Rd=new Map,Xn=a=>{let e=Rd.get(a);if(e)return e;let t=a.normalize("NFKD");return Rd.set(a,t),t},Ad=new Map,ki=a=>{let e=Ad.get(a);if(e)return e;let t=Xn(a.toLowerCase());return Ad.set(a,t),t},xi=class extends Wn{constructor(){super({max:256});}},Za=class extends Wn{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Nd=Symbol("PathScurry setAsCwd"),Je=class{name;root;roots;parent;nocase;isCWD=false;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#n;get nlink(){return this.#n}#o;get uid(){return this.#o}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#d;get blksize(){return this.#d}#a;get ino(){return this.#a}#l;get size(){return this.#l}#r;get blocks(){return this.#r}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#p;get birthtimeMs(){return this.#p}#S;get atime(){return this.#S}#h;get mtime(){return this.#h}#x;get ctime(){return this.#x}#T;get birthtime(){return this.#T}#v;#C;#k;#g;#E;#_;#s;#P;#b;#I;get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=gt,s,n,r,i,o){this.name=e,this.#v=r?ki(e):Xn(e),this.#s=t&zy,this.nocase=r,this.roots=n,this.root=s||this,this.#P=i,this.#k=o.fullpath,this.#E=o.relative,this.#_=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=Ed(o.fs);}depth(){return this.#C!==void 0?this.#C:this.parent?this.#C=this.parent.depth()+1:this.#C=0}childrenCache(){return this.#P}resolve(e){if(!e)return this;let t=this.getRootString(e),n=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#D(n):this.#D(n)}#D(e){let t=this;for(let s of e)t=t.child(s);return t}children(){let e=this.#P.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#P.set(this,t),this.#s&=~Ya,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let s=this.children(),n=this.nocase?ki(e):Xn(e);for(let l of s)if(l.#v===n)return l;let r=this.parent?this.sep:"",i=this.#k?this.#k+r+e:void 0,o=this.newChild(e,gt,{...t,parent:this,fullpath:i});return this.canReaddir()||(o.#s|=Tt),s.push(o),o}relative(){if(this.isCWD)return "";if(this.#E!==void 0)return this.#E;let e=this.name,t=this.parent;if(!t)return this.#E=this.name;let s=t.relative();return s+(!s||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(this.#_!==void 0)return this.#_;let e=this.name,t=this.parent;if(!t)return this.#_=this.fullpathPosix();let s=t.relativePosix();return s+(!s||!t.parent?"":"/")+e}fullpath(){if(this.#k!==void 0)return this.#k;let e=this.name,t=this.parent;if(!t)return this.#k=this.name;let n=t.fullpath()+(t.parent?this.sep:"")+e;return this.#k=n}fullpathPosix(){if(this.#g!==void 0)return this.#g;if(this.sep==="/")return this.#g=this.fullpath();if(!this.parent){let n=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(n)?this.#g=`//?/${n}`:this.#g=n}let e=this.parent,t=e.fullpathPosix(),s=t+(!t||!e.parent?"":"/")+this.name;return this.#g=s}isUnknown(){return (this.#s&mt)===gt}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (this.#s&mt)===Ld}isDirectory(){return (this.#s&mt)===Pt}isCharacterDevice(){return (this.#s&mt)===Pd}isBlockDevice(){return (this.#s&mt)===Dd}isFIFO(){return (this.#s&mt)===Md}isSocket(){return (this.#s&mt)===Od}isSymbolicLink(){return (this.#s&ks)===ks}lstatCached(){return this.#s&Td?this:void 0}readlinkCached(){return this.#b}realpathCached(){return this.#I}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#b)return true;if(!this.parent)return false;let e=this.#s&mt;return !(e!==gt&&e!==ks||this.#s&Ci||this.#s&Tt)}calledReaddir(){return !!(this.#s&Ya)}isENOENT(){return !!(this.#s&Tt)}isNamed(e){return this.nocase?this.#v===ki(e):this.#v===Xn(e)}async readlink(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(t);if(s)return this.#b=s}catch(t){this.#u(t.code);return}}readlinkSync(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(t);if(s)return this.#b=s}catch(t){this.#u(t.code);return}}#L(e){this.#s|=Ya;for(let t=e.provisional;t<e.length;t++){let s=e[t];s&&s.#O();}}#O(){this.#s&Tt||(this.#s=(this.#s|Tt)&Kn,this.#R());}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#O();}#A(){this.#s|=Si,this.#N();}#N(){if(this.#s&Yn)return;let e=this.#s;(e&mt)===Pt&&(e&=Kn),this.#s=e|Yn,this.#R();}#$(e=""){e==="ENOTDIR"||e==="EPERM"?this.#N():e==="ENOENT"?this.#O():this.children().provisional=0;}#F(e=""){e==="ENOTDIR"?this.parent.#N():e==="ENOENT"&&this.#O();}#u(e=""){let t=this.#s;t|=Ci,e==="ENOENT"&&(t|=Tt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Kn),this.#s=t,e==="ENOTDIR"&&this.parent&&this.parent.#N();}#j(e,t){return this.#M(e,t)||this.#B(e,t)}#B(e,t){let s=Xa(e),n=this.newChild(e.name,s,{parent:this}),r=n.#s&mt;return r!==Pt&&r!==ks&&r!==gt&&(n.#s|=Yn),t.unshift(n),t.provisional++,n}#M(e,t){for(let s=t.provisional;s<t.length;s++){let n=t[s];if((this.nocase?ki(e.name):Xn(e.name))===n.#v)return this.#G(e,n,s,t)}}#G(e,t,s,n){let r=t.name;return t.#s=t.#s&Kn|Xa(e),r!==e.name&&(t.name=e.name),s!==n.provisional&&(s===n.length-1?n.pop():n.splice(s,1),n.unshift(t)),n.provisional++,t}async lstat(){if((this.#s&Tt)===0)try{return this.#z(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#F(e.code);}}lstatSync(){if((this.#s&Tt)===0)try{return this.#z(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#F(e.code);}}#z(e){let{atime:t,atimeMs:s,birthtime:n,birthtimeMs:r,blksize:i,blocks:o,ctime:l,ctimeMs:c,dev:u,gid:d,ino:p,mode:h,mtime:g,mtimeMs:f,nlink:b,rdev:y,size:w,uid:C}=e;this.#S=t,this.#f=s,this.#T=n,this.#p=r,this.#d=i,this.#r=o,this.#x=l,this.#m=c,this.#t=u,this.#w=d,this.#a=p,this.#i=h,this.#h=g,this.#y=f,this.#n=b,this.#c=y,this.#l=w,this.#o=C;let k=Xa(e);this.#s=this.#s&Kn|k|Td,k!==gt&&k!==Pt&&k!==ks&&(this.#s|=Yn);}#W=[];#q=false;#H(e){this.#q=false;let t=this.#W.slice();this.#W.length=0,t.forEach(s=>s(null,e));}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);t?e(null,r):queueMicrotask(()=>e(null,r));return}if(this.#W.push(e),this.#q)return;this.#q=true;let n=this.fullpath();this.#e.readdir(n,{withFileTypes:true},(r,i)=>{if(r)this.#$(r.code),s.provisional=0;else {for(let o of i)this.#j(o,s);this.#L(s);}this.#H(s.slice(0,s.provisional));});}#U;async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#U)await this.#U;else {let s=()=>{};this.#U=new Promise(n=>s=n);try{for(let n of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#j(n,e);this.#L(e);}catch(n){this.#$(n.code),e.provisional=0;}this.#U=void 0,s();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let s of this.#e.readdirSync(t,{withFileTypes:!0}))this.#j(s,e);this.#L(e);}catch(s){this.#$(s.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(this.#s&_d)return false;let e=mt&this.#s;return e===gt||e===Pt||e===ks}shouldWalk(e,t){return (this.#s&Pt)===Pt&&!(this.#s&_d)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#I)return this.#I;if(!((Si|Ci|Tt)&this.#s))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#I=this.resolve(e)}catch{this.#A();}}realpathSync(){if(this.#I)return this.#I;if(!((Si|Ci|Tt)&this.#s))try{let e=this.#e.realpathSync(this.fullpath());return this.#I=this.resolve(e)}catch{this.#A();}}[Nd](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),s=[],n=this;for(;n&&n.parent;)t.add(n),n.#E=s.join(this.sep),n.#_=s.join("/"),n=n.parent,s.push("..");for(n=e;n&&n.parent&&!t.has(n);)n.#E=void 0,n.#_=void 0,n=n.parent;}},Ti=class a extends Je{sep="\\";splitSep=qy;constructor(e,t=gt,s,n,r,i,o){super(e,t,s,n,r,i,o);}newChild(e,t=gt,s={}){return new a(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=Wy(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,s]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=s;return this.roots[e]=new tn(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Id,"$1\\"),e===t}},_i=class a extends Je{splitSep="/";sep="/";constructor(e,t=gt,s,n,r,i,o){super(e,t,s,n,r,i,o);}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=gt,s={}){return new a(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Ri=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#n;constructor(e=process.cwd(),t,s,{nocase:n,childrenCacheSize:r=16*1024,fs:i=Vn}={}){this.#n=Ed(i),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new xi,this.#t=new xi,this.#i=new Za(r);let l=o.substring(this.rootPath.length).split(s);if(l.length===1&&!l[0]&&l.pop(),n===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=n,this.root=this.newRoot(this.#n),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,d=t.sep,p=this.rootPath,h=false;for(let g of l){let f=u--;c=c.child(g,{relative:new Array(f).fill("..").join(d),relativePosix:new Array(f).fill("..").join("/"),fullpath:p+=(h?"":d)+g}),h=true;}this.cwd=c;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let r=e.length-1;r>=0;r--){let i=e[r];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let s=this.#e.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpath();return this.#e.set(t,n),n}resolvePosix(...e){let t="";for(let r=e.length-1;r>=0;r--){let i=e[r];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let s=this.#t.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,n),n}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s}=t;if(e.canReaddir()){let n=await e.readdir();return s?n:n.map(r=>r.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true}=t;return e.canReaddir()?s?e.readdirSync():e.readdirSync().map(n=>n.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=await e.readlink();return t?s:s?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=e.readlinkSync();return t?s:s?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=await e.realpath();return t?s:s?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=e.realpathSync();return t?s:s?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=[];(!r||r(e))&&o.push(s?e:e.fullpath());let l=new Set,c=(d,p)=>{l.add(d),d.readdirCB((h,g)=>{if(h)return p(h);let f=g.length;if(!f)return p();let b=()=>{--f===0&&p();};for(let y of g)(!r||r(y))&&o.push(s?y:y.fullpath()),n&&y.isSymbolicLink()?y.realpath().then(w=>w?.isUnknown()?w.lstat():w).then(w=>w?.shouldWalk(l,i)?c(w,b):b()):y.shouldWalk(l,i)?c(y,b):b();},true);},u=e;return new Promise((d,p)=>{c(u,h=>{if(h)return p(h);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=[];(!r||r(e))&&o.push(s?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let d of u){(!r||r(d))&&o.push(s?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(n&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync();}p.shouldWalk(l,i)&&l.add(p);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t;(!r||r(e))&&(yield s?e:e.fullpath());let o=new Set([e]);for(let l of o){let c=l.readdirSync();for(let u of c){(!r||r(u))&&(yield s?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(n&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,i)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=new ss({objectMode:true});(!r||r(e))&&o.write(s?e:e.fullpath());let l=new Set,c=[e],u=0,d=()=>{let p=false;for(;!p;){let h=c.shift();if(!h){u===0&&o.end();return}u++,l.add(h);let g=(b,y,w=false)=>{if(b)return o.emit("error",b);if(n&&!w){let C=[];for(let k of y)k.isSymbolicLink()&&C.push(k.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(C.length){Promise.all(C).then(()=>g(null,y,true));return}}for(let C of y)C&&(!r||r(C))&&(o.write(s?C:C.fullpath())||(p=true));u--;for(let C of y){let k=C.realpathCached()||C;k.shouldWalk(l,i)&&c.push(k);}p&&!o.flowing?o.once("drain",d):f||d();},f=true;h.readdirCB(g,true),f=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=new ss({objectMode:true}),l=new Set;(!r||r(e))&&o.write(s?e:e.fullpath());let c=[e],u=0,d=()=>{let p=false;for(;!p;){let h=c.shift();if(!h){u===0&&o.end();return}u++,l.add(h);let g=h.readdirSync();for(let f of g)(!r||r(f))&&(o.write(s?f:f.fullpath())||(p=true));u--;for(let f of g){let b=f;if(f.isSymbolicLink()){if(!(n&&(b=f.realpathSync())))continue;b.isUnknown()&&b.lstatSync();}b.shouldWalk(l,i)&&c.push(b);}}p&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Nd](t);}},tn=class extends Ri{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,win32,"\\",{...t,nocase:s}),this.nocase=s;for(let n=this.cwd;n;n=n.parent)n.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new Ti(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},sn=class extends Ri{sep="/";constructor(e=process.cwd(),t={}){let{nocase:s=false}=t;super(e,posix,"/",{...t,nocase:s}),this.nocase=s;}parseRootPath(e){return "/"}newRoot(e){return new _i(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Qn=class extends sn{constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,{...t,nocase:s});}};process.platform==="win32"?Ti:_i;var $d=process.platform==="win32"?tn:process.platform==="darwin"?Qn:sn;var Hy=a=>a.length>=1,Jy=a=>a.length>=1,nn=class a{#e;#t;#i;length;#n;#o;#w;#c;#d;#a;#l=true;constructor(e,t,s,n){if(!Hy(e))throw new TypeError("empty pattern list");if(!Jy(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=s,this.#n=n,this.#i===0){if(this.isUNC()){let[r,i,o,l,...c]=this.#e,[u,d,p,h,...g]=this.#t;c[0]===""&&(c.shift(),g.shift());let f=[r,i,o,l,""].join("/"),b=[u,d,p,h,""].join("/");this.#e=[f,...c],this.#t=[b,...g],this.length=this.#e.length;}else if(this.isDrive()||this.isAbsolute()){let[r,...i]=this.#e,[o,...l]=this.#t;i[0]===""&&(i.shift(),l.shift());let c=r+"/",u=o+"/";this.#e=[c,...i],this.#t=[u,...l],this.length=this.#e.length;}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===Ge}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new a(this.#e,this.#t,this.#i+1,this.#n),this.#o.#a=this.#a,this.#o.#d=this.#d,this.#o.#c=this.#c,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#d!==void 0?this.#d:this.#d=this.#n==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#n==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return !(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?false:(this.#l=false,true)}};var Ky=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",rn=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:s,noext:n,noglobstar:r,platform:i=Ky}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:true,nobrace:t,nocase:s,noext:n,noglobstar:r,optimizationLevel:2,platform:i,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new ct(e,this.mmopts);for(let s=0;s<t.set.length;s++){let n=t.set[s],r=t.globParts[s];if(!n||!r)throw new Error("invalid pattern object");for(;n[0]==="."&&r[0]===".";)n.shift(),r.shift();let i=new nn(n,r,0,this.platform),o=new ct(i.globString(),this.mmopts),l=r[r.length-1]==="**",c=i.isAbsolute();c?this.absolute.push(o):this.relative.push(o),l&&(c?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),s=`${t}/`,n=e.relative()||".",r=`${n}/`;for(let i of this.relative)if(i.match(n)||i.match(r))return true;for(let i of this.absolute)if(i.match(t)||i.match(s))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",s=(e.relative()||".")+"/";for(let n of this.relativeChildren)if(n.match(s))return true;for(let n of this.absoluteChildren)if(n.match(t))return true;return false}};var el=class a{store;constructor(e=new Map){this.store=e;}copy(){return new a(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let s=e.fullpath(),n=this.store.get(s);n?n.add(t.globString()):this.store.set(s,new Set([t.globString()]));}},tl=class{store=new Map;add(e,t,s){let n=(t?2:0)|(s?1:0),r=this.store.get(e);this.store.set(e,r===void 0?n:n&r);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},sl=class{store=new Map;add(e,t){if(!e.canReaddir())return;let s=this.store.get(e);s?s.find(n=>n.globString()===t.globString())||s.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},Zn=class a{hasWalkedCache;matches=new tl;subwalks=new sl;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new el;}processPatterns(e,t){this.patterns=t;let s=t.map(n=>[e,n]);for(let[n,r]of s){this.hasWalkedCache.storeWalked(n,r);let i=r.root(),o=r.isAbsolute()&&this.opts.absolute!==false;if(i){n=n.resolve(i==="/"&&this.opts.root!==void 0?this.opts.root:i);let d=r.rest();if(d)r=d;else {this.matches.add(n,true,false);continue}}if(n.isENOENT())continue;let l,c,u=false;for(;typeof(l=r.pattern())=="string"&&(c=r.rest());)n=n.resolve(l),r=c,u=true;if(l=r.pattern(),c=r.rest(),u){if(this.hasWalkedCache.hasWalked(n,r))continue;this.hasWalkedCache.storeWalked(n,r);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(n.resolve(l),o,d);continue}else if(l===Ge){(!n.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(n,r);let d=c?.pattern(),p=c?.rest();if(!c||(d===""||d===".")&&!p)this.matches.add(n,o,d===""||d===".");else if(d===".."){let h=n.parent||n;p?this.hasWalkedCache.hasWalked(h,p)||this.subwalks.add(h,p):this.matches.add(h,o,true);}}else l instanceof RegExp&&this.subwalks.add(n,r);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new a(this.opts,this.hasWalkedCache)}filterEntries(e,t){let s=this.subwalks.get(e),n=this.child();for(let r of t)for(let i of s){let o=i.isAbsolute(),l=i.pattern(),c=i.rest();l===Ge?n.testGlobstar(r,i,c,o):l instanceof RegExp?n.testRegExp(r,l,c,o):n.testString(r,l,c,o);}return n}testGlobstar(e,t,s,n){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,n,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(s&&t.checkFollowGlobstar()?this.subwalks.add(e,s):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(e,r,s.rest(),n);else if(r===".."){let i=e.parent||e;this.subwalks.add(i,s);}else r instanceof RegExp&&this.testRegExp(e,r,s.rest(),n);}}testRegExp(e,t,s,n){t.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}testString(e,t,s,n){e.isNamed(t)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}};var Vy=(a,e)=>typeof a=="string"?new rn([a],e):Array.isArray(a)?new rn(a,e):a,Ai=class{path;patterns;opts;seen=new Set;paused=false;aborted=false;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,s){if(this.patterns=e,this.path=t,this.opts=s,this.#i=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==false,(s.ignore||!this.includeChildMatches)&&(this.#t=Vy(s.ignore??[],s),!this.includeChildMatches&&typeof this.#t.add!="function")){let n="cannot ignore child matches, ignore lacks add() method.";throw new Error(n)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0;}));}#n(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#o(e){return !!this.#t?.childrenIgnored?.(e)}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=this.#e.shift());)e();}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=e.realpathCached()||await e.realpath(),!s)return;e=s;}let r=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let i=await r.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat();}return this.matchCheckTest(r,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#n(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=e.realpathCached()||e.realpathSync(),!s)return;e=s;}let r=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let i=r.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync();}return this.matchCheckTest(r,t)}matchFinish(e,t){if(this.#n(e))return;if(!this.includeChildMatches&&this.#t?.add){let r=`${e.relativePosix()}/**`;this.#t.add(r);}let s=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let n=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(s){let r=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(r+n);}else {let r=this.opts.posix?e.relativePosix():e.relative(),i=this.opts.dotRelative&&!r.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(r?i+r+n:"."+n);}}async match(e,t,s){let n=await this.matchCheck(e,s);n&&this.matchFinish(n,t);}matchSync(e,t,s){let n=this.matchCheckSync(e,s);n&&this.matchFinish(n,t);}walkCB(e,t,s){this.signal?.aborted&&s(),this.walkCB2(e,t,new Zn(this.opts),s);}walkCB2(e,t,s,n){if(this.#o(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2(e,t,s,n));return}s.processPatterns(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||(r++,this.match(o,l,c).then(()=>i()));for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let l=o.readdirCached();o.calledReaddir()?this.walkCB3(o,l,s,i):o.readdirCB((c,u)=>this.walkCB3(o,u,s,i),true);}i();}walkCB3(e,t,s,n){s=s.filterEntries(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||(r++,this.match(o,l,c).then(()=>i()));for(let[o,l]of s.subwalks.entries())r++,this.walkCB2(o,l,s.child(),i);i();}walkCBSync(e,t,s){this.signal?.aborted&&s(),this.walkCB2Sync(e,t,new Zn(this.opts),s);}walkCB2Sync(e,t,s,n){if(this.#o(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,s,n));return}s.processPatterns(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||this.matchSync(o,l,c);for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let l=o.readdirSync();this.walkCB3Sync(o,l,s,i);}i();}walkCB3Sync(e,t,s,n){s=s.filterEntries(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||this.matchSync(o,l,c);for(let[o,l]of s.subwalks.entries())r++,this.walkCB2Sync(o,l,s.child(),i);i();}},er=class extends Ai{matches=new Set;constructor(e,t,s){super(e,t,s);}matchEmit(e){this.matches.add(e);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},tr=class extends Ai{results;constructor(e,t,s){super(e,t,s),this.results=new ss({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(e){this.results.write(e),this.results.flowing||this.pause();}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end());}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Xy=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",_t=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`);}if(this.pattern=e,this.platform=t.platform||Xy,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let l=t.platform==="win32"?tn:t.platform==="darwin"?Qn:t.platform?sn:$d;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",n={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(l=>new ct(l,n)),[i,o]=r.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=i.map((l,c)=>{let u=o[c];if(!u)throw new Error("invalid pattern object");return new nn(l,u,0,this.platform)});}async walk(){return [...await new er(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new er(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new tr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new tr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var nl=(a,e={})=>{Array.isArray(a)||(a=[a]);for(let t of a)if(new ct(t,e).hasMagic())return true;return false};function Ei(a,e={}){return new _t(a,e).streamSync()}function jd(a,e={}){return new _t(a,e).stream()}function Bd(a,e={}){return new _t(a,e).walkSync()}async function Fd(a,e={}){return new _t(a,e).walk()}function Ii(a,e={}){return new _t(a,e).iterateSync()}function Gd(a,e={}){return new _t(a,e).iterate()}var Qy=Ei,Zy=Object.assign(jd,{sync:Ei}),eb=Ii,tb=Object.assign(Gd,{sync:Ii}),sb=Object.assign(Bd,{stream:Ei,iterate:Ii}),on=Object.assign(Fd,{glob:Fd,globSync:Bd,sync:sb,globStream:jd,stream:Zy,globStreamSync:Ei,streamSync:Qy,globIterate:Gd,iterate:tb,globIterateSync:Ii,iterateSync:eb,Glob:_t,hasMagic:nl,escape:Ys,unescape:St});on.glob=on;var sr=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let s=e.split(`
623
+ >>> no match, partial?`,e,p,t,h),p===l))}let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return false}if(i===l&&o===c)return true;if(i===l)return s;if(o===c)return i===l-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return hd(this.pattern,this.options)}parse(e){Gn(e);let t=this.options;if(e==="**")return Ge;if(e==="")return "";let s,n=null;(s=e.match(sy))?n=t.dot?ry:ny:(s=e.match(Hf))?n=(t.nocase?t.dot?Yf:Vf:t.dot?Kf:Jf)(s[1]):(s=e.match(iy))?n=(t.nocase?t.dot?ay:oy:t.dot?ly:cy)(s):(s=e.match(Xf))?n=t.dot?Zf:Qf:(s=e.match(ey))&&(n=ty);let r=Vs.fromGlob(e,this.options).toMMPattern();return n&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:n}),r}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,s=t.noglobstar?py:t.dot?my:gy,n=new Set(t.nocase?["i"]:[]),r=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))n.add(d);return typeof u=="string"?vy(u):u===Ge?Ge:u._src});return c.forEach((u,d)=>{let p=c[d+1],h=c[d-1];u!==Ge||h===Ge||(h===void 0?p!==void 0&&p!==Ge?c[d+1]="(?:\\/|"+s+"\\/)?"+p:c[d]=s:p===void 0?c[d-1]=h+"(?:\\/|"+s+")?":p!==Ge&&(c[d-1]=h+"(?:\\/|\\/"+s+"\\/)"+p,c[d+1]=Ge));}),c.filter(u=>u!==Ge).join("/")}).join("|"),[i,o]=e.length>1?["(?:",")"]:["",""];r="^"+i+r+o+"$",this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...n].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let s=this.options;this.isWindows&&(e=e.split("\\").join("/"));let n=this.slashSplit(e);this.debug(this.pattern,"split",n);let r=this.set;this.debug(this.pattern,"set",r);let i=n[n.length-1];if(!i)for(let o=n.length-2;!i&&o>=0;o--)i=n[o];for(let o=0;o<r.length;o++){let l=r[o],c=n;if(s.matchBase&&l.length===1&&(c=[i]),this.matchOne(c,l,t))return s.flipNegate?true:!this.negate}return s.flipNegate?false:this.negate}static defaults(e){return Xe.defaults(e).Minimatch}};Xe.AST=Vs;Xe.Minimatch=ct;Xe.escape=Ys;Xe.unescape=St;var Xs=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,yd=new Set,Ga=typeof process=="object"&&process?process:{},bd=(a,e,t,s)=>{typeof Ga.emitWarning=="function"?Ga.emitWarning(a,e,t,s):console.error(`[${t}] ${e}: ${a}`);},gi=globalThis.AbortController,fd=globalThis.AbortSignal;if(typeof gi>"u"){fd=class{onabort;_onabort=[];reason;aborted=false;addEventListener(s,n){this._onabort.push(n);}},gi=class{constructor(){e();}signal=new fd;abort(s){if(!this.signal.aborted){this.signal.reason=s,this.signal.aborted=true;for(let n of this.signal._onabort)n(s);this.signal.onabort?.(s);}}};let a=Ga.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{a&&(a=false,bd("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e));};}var wy=a=>!yd.has(a);var es=a=>a&&a===Math.floor(a)&&a>0&&isFinite(a),vd=a=>es(a)?a<=Math.pow(2,8)?Uint8Array:a<=Math.pow(2,16)?Uint16Array:a<=Math.pow(2,32)?Uint32Array:a<=Number.MAX_SAFE_INTEGER?Qs:null:null,Qs=class extends Array{constructor(e){super(e),this.fill(0);}},Ua=class a{heap;length;static#e=false;static create(e){let t=vd(e);if(!t)return [];a.#e=true;let s=new a(e,t);return a.#e=false,s}constructor(e,t){if(!a.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0;}push(e){this.heap[this.length++]=e;}pop(){return this.heap[--this.length]}},Wn=class a{#e;#t;#i;#n;#o;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#d;#a;#l;#r;#f;#y;#m;#p;#S;#h;#x;#T;#v;#C;#k;#g;static unsafeExposeInternals(e){return {starts:e.#T,ttls:e.#v,sizes:e.#x,keyMap:e.#a,keyList:e.#l,valList:e.#r,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#p},free:e.#S,isBackgroundFetch:t=>e.#u(t),backgroundFetch:(t,s,n,r)=>e.#F(t,s,n,r),moveToTail:t=>e.#B(t),indexes:t=>e.#R(t),rindexes:t=>e.#A(t),isStale:t=>e.#b(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#d}get size(){return this.#c}get fetchMethod(){return this.#o}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#n}constructor(e){let{max:t=0,ttl:s,ttlResolution:n=1,ttlAutopurge:r,updateAgeOnGet:i,updateAgeOnHas:o,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:p,maxSize:h=0,maxEntrySize:g=0,sizeCalculation:f,fetchMethod:b,memoMethod:y,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:C,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:T,ignoreFetchAbort:_}=e;if(t!==0&&!es(t))throw new TypeError("max option must be a nonnegative integer");let M=t?vd(t):Array;if(!M)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=h,this.maxEntrySize=g||this.#t,this.sizeCalculation=f,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=y,b!==void 0&&typeof b!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#o=b,this.#k=!!b,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#r=new Array(t).fill(void 0),this.#f=new M(t),this.#y=new M(t),this.#m=0,this.#p=0,this.#S=Ua.create(t),this.#c=0,this.#d=0,typeof c=="function"&&(this.#i=c),typeof u=="function"?(this.#n=u,this.#h=[]):(this.#n=void 0,this.#h=void 0),this.#C=!!this.#i,this.#g=!!this.#n,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!_,this.maxEntrySize!==0){if(this.#t!==0&&!es(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!es(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#I();}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!C,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!o,this.ttlResolution=es(n)||n===0?n:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!es(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#E();}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let F="LRU_CACHE_UNBOUNDED";wy(F)&&(yd.add(F),bd("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",F,a));}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#E(){let e=new Qs(this.#e),t=new Qs(this.#e);this.#v=e,this.#T=t,this.#P=(r,i,o=Xs.now())=>{if(t[r]=i!==0?o:0,e[r]=i,i!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(r)&&this.#M(this.#l[r],"expire");},i+1);l.unref&&l.unref();}},this.#_=r=>{t[r]=e[r]!==0?Xs.now():0;},this.#s=(r,i)=>{if(e[i]){let o=e[i],l=t[i];if(!o||!l)return;r.ttl=o,r.start=l,r.now=s||n();let c=r.now-l;r.remainingTTL=o-c;}};let s=0,n=()=>{let r=Xs.now();if(this.ttlResolution>0){s=r;let i=setTimeout(()=>s=0,this.ttlResolution);i.unref&&i.unref();}return r};this.getRemainingTTL=r=>{let i=this.#a.get(r);if(i===void 0)return 0;let o=e[i],l=t[i];if(!o||!l)return 1/0;let c=(s||n())-l;return o-c},this.#b=r=>{let i=t[r],o=e[r];return !!o&&!!i&&(s||n())-i>o};}#_=()=>{};#s=()=>{};#P=()=>{};#b=()=>false;#I(){let e=new Qs(this.#e);this.#d=0,this.#x=e,this.#D=t=>{this.#d-=e[t],e[t]=0;},this.#O=(t,s,n,r)=>{if(this.#u(s))return 0;if(!es(n))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(n=r(s,t),!es(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return n},this.#L=(t,s,n)=>{if(e[t]=s,this.#t){let r=this.#t-e[t];for(;this.#d>r;)this.#$(true);}this.#d+=e[t],n&&(n.entrySize=s,n.totalCalculatedSize=this.#d);};}#D=e=>{};#L=(e,t,s)=>{};#O=(e,t,s,n)=>{if(s||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;!(!this.#N(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t];}*#A({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#N(t)||((e||!this.#b(t))&&(yield t),t===this.#p));)t=this.#f[t];}#N(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*rentries(){for(let e of this.#A())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*keys(){for(let e of this.#R()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*rkeys(){for(let e of this.#A()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*values(){for(let e of this.#R())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}*rvalues(){for(let e of this.#A())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let s of this.#R()){let n=this.#r[s],r=this.#u(n)?n.__staleWhileFetching:n;if(r!==void 0&&e(r,this.#l[s],this))return this.get(this.#l[s],t)}}forEach(e,t=this){for(let s of this.#R()){let n=this.#r[s],r=this.#u(n)?n.__staleWhileFetching:n;r!==void 0&&e.call(t,r,this.#l[s],this);}}rforEach(e,t=this){for(let s of this.#A()){let n=this.#r[s],r=this.#u(n)?n.__staleWhileFetching:n;r!==void 0&&e.call(t,r,this.#l[s],this);}}purgeStale(){let e=false;for(let t of this.#A({allowStale:true}))this.#b(t)&&(this.#M(this.#l[t],"expire"),e=true);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let s=this.#r[t],n=this.#u(s)?s.__staleWhileFetching:s;if(n===void 0)return;let r={value:n};if(this.#v&&this.#T){let i=this.#v[t],o=this.#T[t];if(i&&o){let l=i-(Xs.now()-o);r.ttl=l,r.start=Date.now();}}return this.#x&&(r.size=this.#x[t]),r}dump(){let e=[];for(let t of this.#R({allowStale:true})){let s=this.#l[t],n=this.#r[t],r=this.#u(n)?n.__staleWhileFetching:n;if(r===void 0||s===void 0)continue;let i={value:r};if(this.#v&&this.#T){i.ttl=this.#v[t];let o=Xs.now()-this.#T[t];i.start=Math.floor(Date.now()-o);}this.#x&&(i.size=this.#x[t]),e.unshift([s,i]);}return e}load(e){this.clear();for(let[t,s]of e){if(s.start){let n=Date.now()-s.start;s.start=Xs.now()-n;}this.set(t,s.value,s);}}set(e,t,s={}){if(t===void 0)return this.delete(e),this;let{ttl:n=this.ttl,start:r,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#O(e,t,s.size||0,o);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),this.#M(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#p:this.#S.length!==0?this.#S.pop():this.#c===this.#e?this.#$(false):this.#c,this.#l[d]=e,this.#r[d]=t,this.#a.set(e,d),this.#f[this.#p]=d,this.#y[d]=this.#p,this.#p=d,this.#c++,this.#L(d,u,l),l&&(l.set="add"),c=false;else {this.#B(d);let p=this.#r[d];if(t!==p){if(this.#k&&this.#u(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=p;h!==void 0&&!i&&(this.#C&&this.#i?.(h,e,"set"),this.#g&&this.#h?.push([h,e,"set"]));}else i||(this.#C&&this.#i?.(p,e,"set"),this.#g&&this.#h?.push([p,e,"set"]));if(this.#D(d),this.#L(d,u,l),this.#r[d]=t,l){l.set="replace";let h=p&&this.#u(p)?p.__staleWhileFetching:p;h!==void 0&&(l.oldValue=h);}}else l&&(l.set="update");}if(n!==0&&!this.#v&&this.#E(),this.#v&&(c||this.#P(d,n,r),l&&this.#s(l,d)),!i&&this.#g&&this.#h){let p=this.#h,h;for(;h=p?.shift();)this.#n?.(...h);}return this}pop(){try{for(;this.#c;){let e=this.#r[this.#m];if(this.#$(!0),this.#u(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#g&&this.#h){let e=this.#h,t;for(;t=e?.shift();)this.#n?.(...t);}}}#$(e){let t=this.#m,s=this.#l[t],n=this.#r[t];return this.#k&&this.#u(n)?n.__abortController.abort(new Error("evicted")):(this.#C||this.#g)&&(this.#C&&this.#i?.(n,s,"evict"),this.#g&&this.#h?.push([n,s,"evict"])),this.#D(t),e&&(this.#l[t]=void 0,this.#r[t]=void 0,this.#S.push(t)),this.#c===1?(this.#m=this.#p=0,this.#S.length=0):this.#m=this.#f[t],this.#a.delete(s),this.#c--,t}has(e,t={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:n}=t,r=this.#a.get(e);if(r!==void 0){let i=this.#r[r];if(this.#u(i)&&i.__staleWhileFetching===void 0)return false;if(this.#b(r))n&&(n.has="stale",this.#s(n,r));else return s&&this.#_(r),n&&(n.has="hit",this.#s(n,r)),true}else n&&(n.has="miss");return false}peek(e,t={}){let{allowStale:s=this.allowStale}=t,n=this.#a.get(e);if(n===void 0||!s&&this.#b(n))return;let r=this.#r[n];return this.#u(r)?r.__staleWhileFetching:r}#F(e,t,s,n){let r=t===void 0?void 0:this.#r[t];if(this.#u(r))return r;let i=new gi,{signal:o}=s;o?.addEventListener("abort",()=>i.abort(o.reason),{signal:i.signal});let l={signal:i.signal,options:s,context:n},c=(f,b=false)=>{let{aborted:y}=i.signal,w=s.ignoreFetchAbort&&f!==void 0;if(s.status&&(y&&!b?(s.status.fetchAborted=true,s.status.fetchError=i.signal.reason,w&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),y&&!w&&!b)return d(i.signal.reason);let C=h;return this.#r[t]===h&&(f===void 0?C.__staleWhileFetching?this.#r[t]=C.__staleWhileFetching:this.#M(e,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(e,f,l.options))),f},u=f=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=f),d(f)),d=f=>{let{aborted:b}=i.signal,y=b&&s.allowStaleOnFetchAbort,w=y||s.allowStaleOnFetchRejection,C=w||s.noDeleteOnFetchRejection,k=h;if(this.#r[t]===h&&(!C||k.__staleWhileFetching===void 0?this.#M(e,"fetch"):y||(this.#r[t]=k.__staleWhileFetching)),w)return s.status&&k.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),k.__staleWhileFetching;if(k.__returned===k)throw f},p=(f,b)=>{let y=this.#o?.(e,r,l);y&&y instanceof Promise&&y.then(w=>f(w===void 0?void 0:w),b),i.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(f(void 0),s.allowStaleOnFetchAbort&&(f=w=>c(w,true)));});};s.status&&(s.status.fetchDispatched=true);let h=new Promise(p).then(c,u),g=Object.assign(h,{__abortController:i,__staleWhileFetching:r,__returned:void 0});return t===void 0?(this.set(e,g,{...l.options,status:void 0}),t=this.#a.get(e)):this.#r[t]=g,g}#u(e){if(!this.#k)return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof gi}async fetch(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:f,forceRefresh:b=false,status:y,signal:w}=t;if(!this.#k)return y&&(y.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:r,status:y});let C={allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:r,ttl:i,noDisposeOnSet:o,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:g,ignoreFetchAbort:h,status:y,signal:w},k=this.#a.get(e);if(k===void 0){y&&(y.fetch="miss");let T=this.#F(e,k,C,f);return T.__returned=T}else {let T=this.#r[k];if(this.#u(T)){let R=s&&T.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",R&&(y.returnedStale=true)),R?T.__staleWhileFetching:T.__returned=T}let _=this.#b(k);if(!b&&!_)return y&&(y.fetch="hit"),this.#B(k),n&&this.#_(k),y&&this.#s(y,k),T;let M=this.#F(e,k,C,f),x=M.__staleWhileFetching!==void 0&&s;return y&&(y.fetch=_?"stale":"refresh",x&&_&&(y.returnedStale=true)),x?M.__staleWhileFetching:M.__returned=M}}async forceFetch(e,t={}){let s=await this.fetch(e,t);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,t={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:n,forceRefresh:r,...i}=t,o=this.get(e,i);if(!r&&o!==void 0)return o;let l=s(e,o,{options:i,context:n});return this.set(e,l,i),l}get(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:i}=t,o=this.#a.get(e);if(o!==void 0){let l=this.#r[o],c=this.#u(l);return i&&this.#s(i,o),this.#b(o)?(i&&(i.get="stale"),c?(i&&s&&l.__staleWhileFetching!==void 0&&(i.returnedStale=true),s?l.__staleWhileFetching:void 0):(r||this.#M(e,"expire"),i&&s&&(i.returnedStale=true),s?l:void 0)):(i&&(i.get="hit"),c?l.__staleWhileFetching:(this.#B(o),n&&this.#_(o),l))}else i&&(i.get="miss");}#j(e,t){this.#y[t]=e,this.#f[e]=t;}#B(e){e!==this.#p&&(e===this.#m?this.#m=this.#f[e]:this.#j(this.#y[e],this.#f[e]),this.#j(this.#p,e),this.#p=e);}delete(e){return this.#M(e,"delete")}#M(e,t){let s=false;if(this.#c!==0){let n=this.#a.get(e);if(n!==void 0)if(s=true,this.#c===1)this.#G(t);else {this.#D(n);let r=this.#r[n];if(this.#u(r)?r.__abortController.abort(new Error("deleted")):(this.#C||this.#g)&&(this.#C&&this.#i?.(r,e,t),this.#g&&this.#h?.push([r,e,t])),this.#a.delete(e),this.#l[n]=void 0,this.#r[n]=void 0,n===this.#p)this.#p=this.#y[n];else if(n===this.#m)this.#m=this.#f[n];else {let i=this.#y[n];this.#f[i]=this.#f[n];let o=this.#f[n];this.#y[o]=this.#y[n];}this.#c--,this.#S.push(n);}}if(this.#g&&this.#h?.length){let n=this.#h,r;for(;r=n?.shift();)this.#n?.(...r);}return s}clear(){return this.#G("delete")}#G(e){for(let t of this.#A({allowStale:true})){let s=this.#r[t];if(this.#u(s))s.__abortController.abort(new Error("deleted"));else {let n=this.#l[t];this.#C&&this.#i?.(s,n,e),this.#g&&this.#h?.push([s,n,e]);}}if(this.#a.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#v&&this.#T&&(this.#v.fill(0),this.#T.fill(0)),this.#x&&this.#x.fill(0),this.#m=0,this.#p=0,this.#S.length=0,this.#d=0,this.#c=0,this.#g&&this.#h){let t=this.#h,s;for(;s=t?.shift();)this.#n?.(...s);}}};var wd=typeof process=="object"&&process?process:{stdout:null,stderr:null},ky=a=>!!a&&typeof a=="object"&&(a instanceof ss||a instanceof xd||Sy(a)||xy(a)),Sy=a=>!!a&&typeof a=="object"&&a instanceof EventEmitter&&typeof a.pipe=="function"&&a.pipe!==xd.Writable.prototype.pipe,xy=a=>!!a&&typeof a=="object"&&a instanceof EventEmitter&&typeof a.write=="function"&&typeof a.end=="function",Ut=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),ts=Symbol("emittedEnd"),hi=Symbol("emittingEnd"),qn=Symbol("emittedError"),fi=Symbol("closed"),Cd=Symbol("read"),yi=Symbol("flush"),kd=Symbol("flushChunk"),xt=Symbol("encoding"),Zs=Symbol("decoder"),Ne=Symbol("flowing"),zn=Symbol("paused"),en=Symbol("resume"),$e=Symbol("buffer"),Qe=Symbol("pipes"),Fe=Symbol("bufferLength"),Wa=Symbol("bufferPush"),bi=Symbol("bufferShift"),He=Symbol("objectMode"),Ee=Symbol("destroyed"),qa=Symbol("error"),za=Symbol("emitData"),Sd=Symbol("emitEnd"),Ha=Symbol("emitEnd2"),Mt=Symbol("async"),Ja=Symbol("abort"),vi=Symbol("aborted"),Hn=Symbol("signal"),Cs=Symbol("dataListeners"),ut=Symbol("discarded"),Jn=a=>Promise.resolve().then(a),Ty=a=>a(),_y=a=>a==="end"||a==="finish"||a==="prefinish",Ry=a=>a instanceof ArrayBuffer||!!a&&typeof a=="object"&&a.constructor&&a.constructor.name==="ArrayBuffer"&&a.byteLength>=0,Ay=a=>!Buffer.isBuffer(a)&&ArrayBuffer.isView(a),wi=class{src;dest;opts;ondrain;constructor(e,t,s){this.src=e,this.dest=t,this.opts=s,this.ondrain=()=>e[en](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Ka=class extends wi{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,s){super(e,t,s),this.proxyErrors=n=>t.emit("error",n),e.on("error",this.proxyErrors);}},Ey=a=>!!a.objectMode,Iy=a=>!a.objectMode&&!!a.encoding&&a.encoding!=="buffer",ss=class extends EventEmitter{[Ne]=false;[zn]=false;[Qe]=[];[$e]=[];[He];[xt];[Mt];[Zs];[Ut]=false;[ts]=false;[hi]=false;[fi]=false;[qn]=null;[Fe]=0;[Ee]=false;[Hn];[vi]=false;[Cs]=0;[ut]=false;writable=true;readable=true;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Ey(t)?(this[He]=true,this[xt]=null):Iy(t)?(this[xt]=t.encoding,this[He]=false):(this[He]=false,this[xt]=null),this[Mt]=!!t.async,this[Zs]=this[xt]?new StringDecoder(this[xt]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[$e]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:s}=t;s&&(this[Hn]=s,s.aborted?this[Ja]():s.addEventListener("abort",()=>this[Ja]()));}get bufferLength(){return this[Fe]}get encoding(){return this[xt]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[He]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Mt]}set async(e){this[Mt]=this[Mt]||!!e;}[Ja](){this[vi]=true,this.emit("abort",this[Hn]?.reason),this.destroy(this[Hn]?.reason);}get aborted(){return this[vi]}set aborted(e){}write(e,t,s){if(this[vi])return false;if(this[Ut])throw new Error("write after end");if(this[Ee])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(s=t,t="utf8"),t||(t="utf8");let n=this[Mt]?Jn:Ty;if(!this[He]&&!Buffer.isBuffer(e)){if(Ay(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Ry(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[He]?(this[Ne]&&this[Fe]!==0&&this[yi](true),this[Ne]?this.emit("data",e):this[Wa](e),this[Fe]!==0&&this.emit("readable"),s&&n(s),this[Ne]):e.length?(typeof e=="string"&&!(t===this[xt]&&!this[Zs]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[xt]&&(e=this[Zs].write(e)),this[Ne]&&this[Fe]!==0&&this[yi](true),this[Ne]?this.emit("data",e):this[Wa](e),this[Fe]!==0&&this.emit("readable"),s&&n(s),this[Ne]):(this[Fe]!==0&&this.emit("readable"),s&&n(s),this[Ne])}read(e){if(this[Ee])return null;if(this[ut]=false,this[Fe]===0||e===0||e&&e>this[Fe])return this[Wt](),null;this[He]&&(e=null),this[$e].length>1&&!this[He]&&(this[$e]=[this[xt]?this[$e].join(""):Buffer.concat(this[$e],this[Fe])]);let t=this[Cd](e||null,this[$e][0]);return this[Wt](),t}[Cd](e,t){if(this[He])this[bi]();else {let s=t;e===s.length||e===null?this[bi]():typeof s=="string"?(this[$e][0]=s.slice(e),t=s.slice(0,e),this[Fe]-=e):(this[$e][0]=s.subarray(e),t=s.subarray(0,e),this[Fe]-=e);}return this.emit("data",t),!this[$e].length&&!this[Ut]&&this.emit("drain"),t}end(e,t,s){return typeof e=="function"&&(s=e,e=void 0),typeof t=="function"&&(s=t,t="utf8"),e!==void 0&&this.write(e,t),s&&this.once("end",s),this[Ut]=true,this.writable=false,(this[Ne]||!this[zn])&&this[Wt](),this}[en](){this[Ee]||(!this[Cs]&&!this[Qe].length&&(this[ut]=true),this[zn]=false,this[Ne]=true,this.emit("resume"),this[$e].length?this[yi]():this[Ut]?this[Wt]():this.emit("drain"));}resume(){return this[en]()}pause(){this[Ne]=false,this[zn]=true,this[ut]=false;}get destroyed(){return this[Ee]}get flowing(){return this[Ne]}get paused(){return this[zn]}[Wa](e){this[He]?this[Fe]+=1:this[Fe]+=e.length,this[$e].push(e);}[bi](){return this[He]?this[Fe]-=1:this[Fe]-=this[$e][0].length,this[$e].shift()}[yi](e=false){do;while(this[kd](this[bi]())&&this[$e].length);!e&&!this[$e].length&&!this[Ut]&&this.emit("drain");}[kd](e){return this.emit("data",e),this[Ne]}pipe(e,t){if(this[Ee])return e;this[ut]=false;let s=this[ts];return t=t||{},e===wd.stdout||e===wd.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,s?t.end&&e.end():(this[Qe].push(t.proxyErrors?new Ka(this,e,t):new wi(this,e,t)),this[Mt]?Jn(()=>this[en]()):this[en]()),e}unpipe(e){let t=this[Qe].find(s=>s.dest===e);t&&(this[Qe].length===1?(this[Ne]&&this[Cs]===0&&(this[Ne]=false),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let s=super.on(e,t);if(e==="data")this[ut]=false,this[Cs]++,!this[Qe].length&&!this[Ne]&&this[en]();else if(e==="readable"&&this[Fe]!==0)super.emit("readable");else if(_y(e)&&this[ts])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[qn]){let n=t;this[Mt]?Jn(()=>n.call(this,this[qn])):n.call(this,this[qn]);}return s}removeListener(e,t){return this.off(e,t)}off(e,t){let s=super.off(e,t);return e==="data"&&(this[Cs]=this.listeners("data").length,this[Cs]===0&&!this[ut]&&!this[Qe].length&&(this[Ne]=false)),s}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[Cs]=0,!this[ut]&&!this[Qe].length&&(this[Ne]=false)),t}get emittedEnd(){return this[ts]}[Wt](){!this[hi]&&!this[ts]&&!this[Ee]&&this[$e].length===0&&this[Ut]&&(this[hi]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[fi]&&this.emit("close"),this[hi]=false);}emit(e,...t){let s=t[0];if(e!=="error"&&e!=="close"&&e!==Ee&&this[Ee])return false;if(e==="data")return !this[He]&&!s?false:this[Mt]?(Jn(()=>this[za](s)),true):this[za](s);if(e==="end")return this[Sd]();if(e==="close"){if(this[fi]=true,!this[ts]&&!this[Ee])return false;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(e==="error"){this[qn]=s,super.emit(qa,s);let r=!this[Hn]||this.listeners("error").length?super.emit("error",s):false;return this[Wt](),r}else if(e==="resume"){let r=super.emit("resume");return this[Wt](),r}else if(e==="finish"||e==="prefinish"){let r=super.emit(e);return this.removeAllListeners(e),r}let n=super.emit(e,...t);return this[Wt](),n}[za](e){for(let s of this[Qe])s.dest.write(e)===false&&this.pause();let t=this[ut]?false:super.emit("data",e);return this[Wt](),t}[Sd](){return this[ts]?false:(this[ts]=true,this.readable=false,this[Mt]?(Jn(()=>this[Ha]()),true):this[Ha]())}[Ha](){if(this[Zs]){let t=this[Zs].end();if(t){for(let s of this[Qe])s.dest.write(t);this[ut]||super.emit("data",t);}}for(let t of this[Qe])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[He]||(e.dataLength=0);let t=this.promise();return this.on("data",s=>{e.push(s),this[He]||(e.dataLength+=s.length);}),await t,e}async concat(){if(this[He])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[xt]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Ee,()=>t(new Error("stream destroyed"))),this.on("error",s=>t(s)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[ut]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:false,value:n});if(this[Ut])return t();let r,i,o=d=>{this.off("data",l),this.off("end",c),this.off(Ee,u),t(),i(d);},l=d=>{this.off("error",o),this.off("end",c),this.off(Ee,u),this.pause(),r({value:d,done:!!this[Ut]});},c=()=>{this.off("error",o),this.off("data",l),this.off(Ee,u),t(),r({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,p)=>{i=p,r=d,this.once(Ee,u),this.once("error",o),this.once("end",c),this.once("data",l);})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[ut]=false;let e=false,t=()=>(this.pause(),this.off(qa,t),this.off(Ee,t),this.off("end",t),e=true,{done:true,value:void 0}),s=()=>{if(e)return t();let n=this.read();return n===null?t():{done:false,value:n}};return this.once("end",t),this.once(qa,t),this.once(Ee,t),{next:s,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Ee])return e?this.emit("error",e):this.emit(Ee),this;this[Ee]=true,this[ut]=true,this[$e].length=0,this[Fe]=0;let t=this;return typeof t.close=="function"&&!this[fi]&&t.close(),e?this.emit("error",e):this.emit(Ee),this}static get isStream(){return ky}};var jy=realpathSync.native,Vn={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:jy,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Ed=a=>!a||a===Vn||a===Me?Vn:{...Vn,...a,promises:{...Vn.promises,...a.promises||{}}},Id=/^\\\\\?\\([a-z]:)\\?$/i,qy=a=>a.replace(/\//g,"\\").replace(Id,"$1\\"),zy=/[\\\/]/,gt=0,Md=1,Pd=2,Pt=4,Dd=6,Ld=8,ks=10,Od=12,mt=15,Kn=~mt,Ya=16,Td=32,Yn=64,Tt=128,Ci=256,Si=512,_d=Yn|Tt|Si,Hy=1023,Xa=a=>a.isFile()?Ld:a.isDirectory()?Pt:a.isSymbolicLink()?ks:a.isCharacterDevice()?Pd:a.isBlockDevice()?Dd:a.isSocket()?Od:a.isFIFO()?Md:gt,Rd=new Map,Xn=a=>{let e=Rd.get(a);if(e)return e;let t=a.normalize("NFKD");return Rd.set(a,t),t},Ad=new Map,ki=a=>{let e=Ad.get(a);if(e)return e;let t=Xn(a.toLowerCase());return Ad.set(a,t),t},xi=class extends Wn{constructor(){super({max:256});}},Za=class extends Wn{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Nd=Symbol("PathScurry setAsCwd"),Je=class{name;root;roots;parent;nocase;isCWD=false;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#n;get nlink(){return this.#n}#o;get uid(){return this.#o}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#d;get blksize(){return this.#d}#a;get ino(){return this.#a}#l;get size(){return this.#l}#r;get blocks(){return this.#r}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#p;get birthtimeMs(){return this.#p}#S;get atime(){return this.#S}#h;get mtime(){return this.#h}#x;get ctime(){return this.#x}#T;get birthtime(){return this.#T}#v;#C;#k;#g;#E;#_;#s;#P;#b;#I;get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=gt,s,n,r,i,o){this.name=e,this.#v=r?ki(e):Xn(e),this.#s=t&Hy,this.nocase=r,this.roots=n,this.root=s||this,this.#P=i,this.#k=o.fullpath,this.#E=o.relative,this.#_=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=Ed(o.fs);}depth(){return this.#C!==void 0?this.#C:this.parent?this.#C=this.parent.depth()+1:this.#C=0}childrenCache(){return this.#P}resolve(e){if(!e)return this;let t=this.getRootString(e),n=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#D(n):this.#D(n)}#D(e){let t=this;for(let s of e)t=t.child(s);return t}children(){let e=this.#P.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#P.set(this,t),this.#s&=~Ya,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let s=this.children(),n=this.nocase?ki(e):Xn(e);for(let l of s)if(l.#v===n)return l;let r=this.parent?this.sep:"",i=this.#k?this.#k+r+e:void 0,o=this.newChild(e,gt,{...t,parent:this,fullpath:i});return this.canReaddir()||(o.#s|=Tt),s.push(o),o}relative(){if(this.isCWD)return "";if(this.#E!==void 0)return this.#E;let e=this.name,t=this.parent;if(!t)return this.#E=this.name;let s=t.relative();return s+(!s||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(this.#_!==void 0)return this.#_;let e=this.name,t=this.parent;if(!t)return this.#_=this.fullpathPosix();let s=t.relativePosix();return s+(!s||!t.parent?"":"/")+e}fullpath(){if(this.#k!==void 0)return this.#k;let e=this.name,t=this.parent;if(!t)return this.#k=this.name;let n=t.fullpath()+(t.parent?this.sep:"")+e;return this.#k=n}fullpathPosix(){if(this.#g!==void 0)return this.#g;if(this.sep==="/")return this.#g=this.fullpath();if(!this.parent){let n=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(n)?this.#g=`//?/${n}`:this.#g=n}let e=this.parent,t=e.fullpathPosix(),s=t+(!t||!e.parent?"":"/")+this.name;return this.#g=s}isUnknown(){return (this.#s&mt)===gt}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (this.#s&mt)===Ld}isDirectory(){return (this.#s&mt)===Pt}isCharacterDevice(){return (this.#s&mt)===Pd}isBlockDevice(){return (this.#s&mt)===Dd}isFIFO(){return (this.#s&mt)===Md}isSocket(){return (this.#s&mt)===Od}isSymbolicLink(){return (this.#s&ks)===ks}lstatCached(){return this.#s&Td?this:void 0}readlinkCached(){return this.#b}realpathCached(){return this.#I}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#b)return true;if(!this.parent)return false;let e=this.#s&mt;return !(e!==gt&&e!==ks||this.#s&Ci||this.#s&Tt)}calledReaddir(){return !!(this.#s&Ya)}isENOENT(){return !!(this.#s&Tt)}isNamed(e){return this.nocase?this.#v===ki(e):this.#v===Xn(e)}async readlink(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(t);if(s)return this.#b=s}catch(t){this.#u(t.code);return}}readlinkSync(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(t);if(s)return this.#b=s}catch(t){this.#u(t.code);return}}#L(e){this.#s|=Ya;for(let t=e.provisional;t<e.length;t++){let s=e[t];s&&s.#O();}}#O(){this.#s&Tt||(this.#s=(this.#s|Tt)&Kn,this.#R());}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#O();}#A(){this.#s|=Si,this.#N();}#N(){if(this.#s&Yn)return;let e=this.#s;(e&mt)===Pt&&(e&=Kn),this.#s=e|Yn,this.#R();}#$(e=""){e==="ENOTDIR"||e==="EPERM"?this.#N():e==="ENOENT"?this.#O():this.children().provisional=0;}#F(e=""){e==="ENOTDIR"?this.parent.#N():e==="ENOENT"&&this.#O();}#u(e=""){let t=this.#s;t|=Ci,e==="ENOENT"&&(t|=Tt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Kn),this.#s=t,e==="ENOTDIR"&&this.parent&&this.parent.#N();}#j(e,t){return this.#M(e,t)||this.#B(e,t)}#B(e,t){let s=Xa(e),n=this.newChild(e.name,s,{parent:this}),r=n.#s&mt;return r!==Pt&&r!==ks&&r!==gt&&(n.#s|=Yn),t.unshift(n),t.provisional++,n}#M(e,t){for(let s=t.provisional;s<t.length;s++){let n=t[s];if((this.nocase?ki(e.name):Xn(e.name))===n.#v)return this.#G(e,n,s,t)}}#G(e,t,s,n){let r=t.name;return t.#s=t.#s&Kn|Xa(e),r!==e.name&&(t.name=e.name),s!==n.provisional&&(s===n.length-1?n.pop():n.splice(s,1),n.unshift(t)),n.provisional++,t}async lstat(){if((this.#s&Tt)===0)try{return this.#z(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#F(e.code);}}lstatSync(){if((this.#s&Tt)===0)try{return this.#z(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#F(e.code);}}#z(e){let{atime:t,atimeMs:s,birthtime:n,birthtimeMs:r,blksize:i,blocks:o,ctime:l,ctimeMs:c,dev:u,gid:d,ino:p,mode:h,mtime:g,mtimeMs:f,nlink:b,rdev:y,size:w,uid:C}=e;this.#S=t,this.#f=s,this.#T=n,this.#p=r,this.#d=i,this.#r=o,this.#x=l,this.#m=c,this.#t=u,this.#w=d,this.#a=p,this.#i=h,this.#h=g,this.#y=f,this.#n=b,this.#c=y,this.#l=w,this.#o=C;let k=Xa(e);this.#s=this.#s&Kn|k|Td,k!==gt&&k!==Pt&&k!==ks&&(this.#s|=Yn);}#W=[];#q=false;#H(e){this.#q=false;let t=this.#W.slice();this.#W.length=0,t.forEach(s=>s(null,e));}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);t?e(null,r):queueMicrotask(()=>e(null,r));return}if(this.#W.push(e),this.#q)return;this.#q=true;let n=this.fullpath();this.#e.readdir(n,{withFileTypes:true},(r,i)=>{if(r)this.#$(r.code),s.provisional=0;else {for(let o of i)this.#j(o,s);this.#L(s);}this.#H(s.slice(0,s.provisional));});}#U;async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#U)await this.#U;else {let s=()=>{};this.#U=new Promise(n=>s=n);try{for(let n of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#j(n,e);this.#L(e);}catch(n){this.#$(n.code),e.provisional=0;}this.#U=void 0,s();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let s of this.#e.readdirSync(t,{withFileTypes:!0}))this.#j(s,e);this.#L(e);}catch(s){this.#$(s.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(this.#s&_d)return false;let e=mt&this.#s;return e===gt||e===Pt||e===ks}shouldWalk(e,t){return (this.#s&Pt)===Pt&&!(this.#s&_d)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#I)return this.#I;if(!((Si|Ci|Tt)&this.#s))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#I=this.resolve(e)}catch{this.#A();}}realpathSync(){if(this.#I)return this.#I;if(!((Si|Ci|Tt)&this.#s))try{let e=this.#e.realpathSync(this.fullpath());return this.#I=this.resolve(e)}catch{this.#A();}}[Nd](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),s=[],n=this;for(;n&&n.parent;)t.add(n),n.#E=s.join(this.sep),n.#_=s.join("/"),n=n.parent,s.push("..");for(n=e;n&&n.parent&&!t.has(n);)n.#E=void 0,n.#_=void 0,n=n.parent;}},Ti=class a extends Je{sep="\\";splitSep=zy;constructor(e,t=gt,s,n,r,i,o){super(e,t,s,n,r,i,o);}newChild(e,t=gt,s={}){return new a(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=qy(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,s]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=s;return this.roots[e]=new tn(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Id,"$1\\"),e===t}},_i=class a extends Je{splitSep="/";sep="/";constructor(e,t=gt,s,n,r,i,o){super(e,t,s,n,r,i,o);}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=gt,s={}){return new a(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Ri=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#n;constructor(e=process.cwd(),t,s,{nocase:n,childrenCacheSize:r=16*1024,fs:i=Vn}={}){this.#n=Ed(i),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new xi,this.#t=new xi,this.#i=new Za(r);let l=o.substring(this.rootPath.length).split(s);if(l.length===1&&!l[0]&&l.pop(),n===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=n,this.root=this.newRoot(this.#n),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,d=t.sep,p=this.rootPath,h=false;for(let g of l){let f=u--;c=c.child(g,{relative:new Array(f).fill("..").join(d),relativePosix:new Array(f).fill("..").join("/"),fullpath:p+=(h?"":d)+g}),h=true;}this.cwd=c;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let r=e.length-1;r>=0;r--){let i=e[r];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let s=this.#e.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpath();return this.#e.set(t,n),n}resolvePosix(...e){let t="";for(let r=e.length-1;r>=0;r--){let i=e[r];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let s=this.#t.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,n),n}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s}=t;if(e.canReaddir()){let n=await e.readdir();return s?n:n.map(r=>r.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true}=t;return e.canReaddir()?s?e.readdirSync():e.readdirSync().map(n=>n.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=await e.readlink();return t?s:s?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=e.readlinkSync();return t?s:s?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=await e.realpath();return t?s:s?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e.withFileTypes,e=this.cwd);let s=e.realpathSync();return t?s:s?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=[];(!r||r(e))&&o.push(s?e:e.fullpath());let l=new Set,c=(d,p)=>{l.add(d),d.readdirCB((h,g)=>{if(h)return p(h);let f=g.length;if(!f)return p();let b=()=>{--f===0&&p();};for(let y of g)(!r||r(y))&&o.push(s?y:y.fullpath()),n&&y.isSymbolicLink()?y.realpath().then(w=>w?.isUnknown()?w.lstat():w).then(w=>w?.shouldWalk(l,i)?c(w,b):b()):y.shouldWalk(l,i)?c(y,b):b();},true);},u=e;return new Promise((d,p)=>{c(u,h=>{if(h)return p(h);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=[];(!r||r(e))&&o.push(s?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let d of u){(!r||r(d))&&o.push(s?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(n&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync();}p.shouldWalk(l,i)&&l.add(p);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t;(!r||r(e))&&(yield s?e:e.fullpath());let o=new Set([e]);for(let l of o){let c=l.readdirSync();for(let u of c){(!r||r(u))&&(yield s?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(n&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,i)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=new ss({objectMode:true});(!r||r(e))&&o.write(s?e:e.fullpath());let l=new Set,c=[e],u=0,d=()=>{let p=false;for(;!p;){let h=c.shift();if(!h){u===0&&o.end();return}u++,l.add(h);let g=(b,y,w=false)=>{if(b)return o.emit("error",b);if(n&&!w){let C=[];for(let k of y)k.isSymbolicLink()&&C.push(k.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(C.length){Promise.all(C).then(()=>g(null,y,true));return}}for(let C of y)C&&(!r||r(C))&&(o.write(s?C:C.fullpath())||(p=true));u--;for(let C of y){let k=C.realpathCached()||C;k.shouldWalk(l,i)&&c.push(k);}p&&!o.flowing?o.once("drain",d):f||d();},f=true;h.readdirCB(g,true),f=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Je||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:r,walkFilter:i}=t,o=new ss({objectMode:true}),l=new Set;(!r||r(e))&&o.write(s?e:e.fullpath());let c=[e],u=0,d=()=>{let p=false;for(;!p;){let h=c.shift();if(!h){u===0&&o.end();return}u++,l.add(h);let g=h.readdirSync();for(let f of g)(!r||r(f))&&(o.write(s?f:f.fullpath())||(p=true));u--;for(let f of g){let b=f;if(f.isSymbolicLink()){if(!(n&&(b=f.realpathSync())))continue;b.isUnknown()&&b.lstatSync();}b.shouldWalk(l,i)&&c.push(b);}}p&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Nd](t);}},tn=class extends Ri{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,win32,"\\",{...t,nocase:s}),this.nocase=s;for(let n=this.cwd;n;n=n.parent)n.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new Ti(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},sn=class extends Ri{sep="/";constructor(e=process.cwd(),t={}){let{nocase:s=false}=t;super(e,posix,"/",{...t,nocase:s}),this.nocase=s;}parseRootPath(e){return "/"}newRoot(e){return new _i(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Qn=class extends sn{constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,{...t,nocase:s});}};process.platform==="win32"?Ti:_i;var $d=process.platform==="win32"?tn:process.platform==="darwin"?Qn:sn;var Jy=a=>a.length>=1,Ky=a=>a.length>=1,nn=class a{#e;#t;#i;length;#n;#o;#w;#c;#d;#a;#l=true;constructor(e,t,s,n){if(!Jy(e))throw new TypeError("empty pattern list");if(!Ky(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=s,this.#n=n,this.#i===0){if(this.isUNC()){let[r,i,o,l,...c]=this.#e,[u,d,p,h,...g]=this.#t;c[0]===""&&(c.shift(),g.shift());let f=[r,i,o,l,""].join("/"),b=[u,d,p,h,""].join("/");this.#e=[f,...c],this.#t=[b,...g],this.length=this.#e.length;}else if(this.isDrive()||this.isAbsolute()){let[r,...i]=this.#e,[o,...l]=this.#t;i[0]===""&&(i.shift(),l.shift());let c=r+"/",u=o+"/";this.#e=[c,...i],this.#t=[u,...l],this.length=this.#e.length;}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===Ge}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new a(this.#e,this.#t,this.#i+1,this.#n),this.#o.#a=this.#a,this.#o.#d=this.#d,this.#o.#c=this.#c,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#d!==void 0?this.#d:this.#d=this.#n==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#n==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return !(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?false:(this.#l=false,true)}};var Vy=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",rn=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:s,noext:n,noglobstar:r,platform:i=Vy}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:true,nobrace:t,nocase:s,noext:n,noglobstar:r,optimizationLevel:2,platform:i,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new ct(e,this.mmopts);for(let s=0;s<t.set.length;s++){let n=t.set[s],r=t.globParts[s];if(!n||!r)throw new Error("invalid pattern object");for(;n[0]==="."&&r[0]===".";)n.shift(),r.shift();let i=new nn(n,r,0,this.platform),o=new ct(i.globString(),this.mmopts),l=r[r.length-1]==="**",c=i.isAbsolute();c?this.absolute.push(o):this.relative.push(o),l&&(c?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),s=`${t}/`,n=e.relative()||".",r=`${n}/`;for(let i of this.relative)if(i.match(n)||i.match(r))return true;for(let i of this.absolute)if(i.match(t)||i.match(s))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",s=(e.relative()||".")+"/";for(let n of this.relativeChildren)if(n.match(s))return true;for(let n of this.absoluteChildren)if(n.match(t))return true;return false}};var el=class a{store;constructor(e=new Map){this.store=e;}copy(){return new a(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let s=e.fullpath(),n=this.store.get(s);n?n.add(t.globString()):this.store.set(s,new Set([t.globString()]));}},tl=class{store=new Map;add(e,t,s){let n=(t?2:0)|(s?1:0),r=this.store.get(e);this.store.set(e,r===void 0?n:n&r);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},sl=class{store=new Map;add(e,t){if(!e.canReaddir())return;let s=this.store.get(e);s?s.find(n=>n.globString()===t.globString())||s.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},Zn=class a{hasWalkedCache;matches=new tl;subwalks=new sl;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new el;}processPatterns(e,t){this.patterns=t;let s=t.map(n=>[e,n]);for(let[n,r]of s){this.hasWalkedCache.storeWalked(n,r);let i=r.root(),o=r.isAbsolute()&&this.opts.absolute!==false;if(i){n=n.resolve(i==="/"&&this.opts.root!==void 0?this.opts.root:i);let d=r.rest();if(d)r=d;else {this.matches.add(n,true,false);continue}}if(n.isENOENT())continue;let l,c,u=false;for(;typeof(l=r.pattern())=="string"&&(c=r.rest());)n=n.resolve(l),r=c,u=true;if(l=r.pattern(),c=r.rest(),u){if(this.hasWalkedCache.hasWalked(n,r))continue;this.hasWalkedCache.storeWalked(n,r);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(n.resolve(l),o,d);continue}else if(l===Ge){(!n.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(n,r);let d=c?.pattern(),p=c?.rest();if(!c||(d===""||d===".")&&!p)this.matches.add(n,o,d===""||d===".");else if(d===".."){let h=n.parent||n;p?this.hasWalkedCache.hasWalked(h,p)||this.subwalks.add(h,p):this.matches.add(h,o,true);}}else l instanceof RegExp&&this.subwalks.add(n,r);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new a(this.opts,this.hasWalkedCache)}filterEntries(e,t){let s=this.subwalks.get(e),n=this.child();for(let r of t)for(let i of s){let o=i.isAbsolute(),l=i.pattern(),c=i.rest();l===Ge?n.testGlobstar(r,i,c,o):l instanceof RegExp?n.testRegExp(r,l,c,o):n.testString(r,l,c,o);}return n}testGlobstar(e,t,s,n){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,n,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(s&&t.checkFollowGlobstar()?this.subwalks.add(e,s):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(e,r,s.rest(),n);else if(r===".."){let i=e.parent||e;this.subwalks.add(i,s);}else r instanceof RegExp&&this.testRegExp(e,r,s.rest(),n);}}testRegExp(e,t,s,n){t.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}testString(e,t,s,n){e.isNamed(t)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}};var Yy=(a,e)=>typeof a=="string"?new rn([a],e):Array.isArray(a)?new rn(a,e):a,Ai=class{path;patterns;opts;seen=new Set;paused=false;aborted=false;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,s){if(this.patterns=e,this.path=t,this.opts=s,this.#i=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==false,(s.ignore||!this.includeChildMatches)&&(this.#t=Yy(s.ignore??[],s),!this.includeChildMatches&&typeof this.#t.add!="function")){let n="cannot ignore child matches, ignore lacks add() method.";throw new Error(n)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0;}));}#n(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#o(e){return !!this.#t?.childrenIgnored?.(e)}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=this.#e.shift());)e();}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=e.realpathCached()||await e.realpath(),!s)return;e=s;}let r=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let i=await r.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat();}return this.matchCheckTest(r,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#n(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=e.realpathCached()||e.realpathSync(),!s)return;e=s;}let r=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let i=r.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync();}return this.matchCheckTest(r,t)}matchFinish(e,t){if(this.#n(e))return;if(!this.includeChildMatches&&this.#t?.add){let r=`${e.relativePosix()}/**`;this.#t.add(r);}let s=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let n=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(s){let r=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(r+n);}else {let r=this.opts.posix?e.relativePosix():e.relative(),i=this.opts.dotRelative&&!r.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(r?i+r+n:"."+n);}}async match(e,t,s){let n=await this.matchCheck(e,s);n&&this.matchFinish(n,t);}matchSync(e,t,s){let n=this.matchCheckSync(e,s);n&&this.matchFinish(n,t);}walkCB(e,t,s){this.signal?.aborted&&s(),this.walkCB2(e,t,new Zn(this.opts),s);}walkCB2(e,t,s,n){if(this.#o(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2(e,t,s,n));return}s.processPatterns(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||(r++,this.match(o,l,c).then(()=>i()));for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let l=o.readdirCached();o.calledReaddir()?this.walkCB3(o,l,s,i):o.readdirCB((c,u)=>this.walkCB3(o,u,s,i),true);}i();}walkCB3(e,t,s,n){s=s.filterEntries(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||(r++,this.match(o,l,c).then(()=>i()));for(let[o,l]of s.subwalks.entries())r++,this.walkCB2(o,l,s.child(),i);i();}walkCBSync(e,t,s){this.signal?.aborted&&s(),this.walkCB2Sync(e,t,new Zn(this.opts),s);}walkCB2Sync(e,t,s,n){if(this.#o(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,s,n));return}s.processPatterns(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||this.matchSync(o,l,c);for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let l=o.readdirSync();this.walkCB3Sync(o,l,s,i);}i();}walkCB3Sync(e,t,s,n){s=s.filterEntries(e,t);let r=1,i=()=>{--r===0&&n();};for(let[o,l,c]of s.matches.entries())this.#n(o)||this.matchSync(o,l,c);for(let[o,l]of s.subwalks.entries())r++,this.walkCB2Sync(o,l,s.child(),i);i();}},er=class extends Ai{matches=new Set;constructor(e,t,s){super(e,t,s);}matchEmit(e){this.matches.add(e);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},tr=class extends Ai{results;constructor(e,t,s){super(e,t,s),this.results=new ss({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(e){this.results.write(e),this.results.flowing||this.pause();}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end());}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Qy=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",_t=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`);}if(this.pattern=e,this.platform=t.platform||Qy,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let l=t.platform==="win32"?tn:t.platform==="darwin"?Qn:t.platform?sn:$d;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",n={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(l=>new ct(l,n)),[i,o]=r.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=i.map((l,c)=>{let u=o[c];if(!u)throw new Error("invalid pattern object");return new nn(l,u,0,this.platform)});}async walk(){return [...await new er(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new er(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new tr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new tr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var nl=(a,e={})=>{Array.isArray(a)||(a=[a]);for(let t of a)if(new ct(t,e).hasMagic())return true;return false};function Ei(a,e={}){return new _t(a,e).streamSync()}function jd(a,e={}){return new _t(a,e).stream()}function Bd(a,e={}){return new _t(a,e).walkSync()}async function Fd(a,e={}){return new _t(a,e).walk()}function Ii(a,e={}){return new _t(a,e).iterateSync()}function Gd(a,e={}){return new _t(a,e).iterate()}var Zy=Ei,eb=Object.assign(jd,{sync:Ei}),tb=Ii,sb=Object.assign(Gd,{sync:Ii}),nb=Object.assign(Bd,{stream:Ei,iterate:Ii}),on=Object.assign(Fd,{glob:Fd,globSync:Bd,sync:nb,globStream:jd,stream:eb,globStreamSync:Ei,streamSync:Zy,globIterate:Gd,iterate:sb,globIterateSync:Ii,iterateSync:tb,Glob:_t,hasMagic:nl,escape:Ys,unescape:St});on.glob=on;var sr=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let s=e.split(`
624
624
  `),n=[],r={class:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(\s+extends\s+\w+)?(\s+implements\s+[\w,\s]+)?/,interface:/^(\s*)(export\s+)?interface\s+(\w+)(\s+extends\s+[\w,\s]+)?/,type:/^(\s*)(export\s+)?type\s+(\w+)\s*[=<]/,enum:/^(\s*)(export\s+)?enum\s+(\w+)/,function:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*[<(]/,constFunction:/^(\s*)(export\s+)?(const|let|var)\s+(\w+)\s*[=:]\s*(async\s+)?(\([^)]*\)|[a-zA-Z_]\w*)\s*(=>|:.*=>)/,variable:/^(\s*)(export\s+)?(const|let|var)\s+(\w+)\s*[=:]/,method:/^(\s+)(public\s+|private\s+|protected\s+)?(static\s+)?(async\s+)?(\w+)\s*[<(]/,property:/^(\s+)(public\s+|private\s+|protected\s+)?(static\s+)?(readonly\s+)?(\w+)\s*[=:?]/},i=null,o=0;for(let l=0;l<s.length;l++){let c=s[l],u=l+1;if(i){let f=c.match(/^(\s*)/)?.[1].length||0;c.trim()&&f<=o&&!c.match(/^\s*[})\]]/)&&(i.endLine=l,n.push(i),i=null);}if(c.trim().startsWith("//")||c.trim().startsWith("/*")||!c.trim())continue;let d=c.match(r.class);if(d){if(i&&(i.endLine=l,n.push(i)),o=d[1].length,i={name:d[4],kind:"class",startLine:u,endLine:this.findSymbolEnd(s,l),children:[]},l>0){let f=s[l-1].trim();f.startsWith("/**")||f.startsWith("/*")?i.docstring=this.extractDocstring(s,l-1):f.startsWith("//")&&(i.docstring=f.replace(/^\/\/\s*/,""));}continue}let p=c.match(r.interface);if(p){n.push({name:p[3],kind:"interface",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let h=c.match(r.type);if(h){n.push({name:h[3],kind:"type",startLine:u,endLine:this.findTypeEnd(s,l)});continue}let g=c.match(r.enum);if(g){n.push({name:g[3],kind:"enum",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}if(!i){let f=c.match(r.function);if(f){n.push({name:f[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let b=c.match(r.constFunction);if(b){n.push({name:b[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let y=c.match(r.variable);if(y&&!r.constFunction.test(c)){n.push({name:y[4],kind:"variable",startLine:u,endLine:u});continue}}if(i){let f=c.match(r.method);if(f&&!["if","for","while","switch","catch","constructor"].includes(f[5])){let y={name:f[5],kind:(f[5]==="constructor","method"),startLine:u,endLine:this.findSymbolEnd(s,l),parent:i.name};i.children.push(y);continue}let b=c.match(r.property);if(b&&!["if","for","while","switch","catch","return","const","let","var"].includes(b[5])){let y={name:b[5],kind:"variable",startLine:u,endLine:u,parent:i.name};i.children.push(y);}}}return i&&(i.endLine=s.length,n.push(i)),n}findSymbolEnd(e,t){return Zt(e,t)}findTypeEnd(e,t){for(let s=t;s<e.length;s++){let n=e[s];if(n.includes(";")||s>t&&/^(export|type|interface|class|function|const|let|var)/.test(n.trim()))return s+1}return t+1}extractDocstring(e,t){let s=[],n=t;for(;n>=0;){let r=e[n].trim();if(r.startsWith("/**")||r.startsWith("/*"))break;n--;}for(let r=n;r<=t;r++){let i=e[r].trim();i=i.replace(/^\/\*\*?\s*/,"").replace(/\*\/\s*$/,"").replace(/^\*\s?/,""),i&&s.push(i);}return s.join(`
625
625
  `)}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|async\\s+function|const|let|var)\\s+${s}\\s*[=(<]`;case "class":return `class\\s+${s}(\\s+extends|\\s+implements|\\s*\\{)`;case "interface":return `interface\\s+${s}(\\s+extends|\\s*\\{)`;case "type":return `type\\s+${s}\\s*[=<]`;case "enum":return `enum\\s+${s}\\s*\\{`;case "method":return `(async\\s+)?${s}\\s*\\(`;case "variable":return `(const|let|var)\\s+${s}\\s*[=:]`;default:return `(function|class|interface|type|enum|const|let|var)\\s+${s}|${s}\\s*(=|\\()`}}};var nr=class{languageId="python";extensions=[".py",".pyw"];async parse(e,t){let s=e.split(`
626
626
  `),n=[],r={class:/^(\s*)class\s+(\w+)(\s*\([^)]*\))?\s*:/,function:/^(\s*)(async\s+)?def\s+(\w+)\s*\(/,variable:/^([A-Z][A-Z0-9_]*)\s*[=:]/},i=null,o=-1;for(let l=0;l<s.length;l++){let c=s[l],u=l+1,d=c.match(/^(\s*)/)?.[1].length||0;if(i&&c.trim()&&d<=o&&(i.endLine=l,n.push(i),i=null,o=-1),c.trim().startsWith("#")||!c.trim())continue;let p=c.match(r.class);if(p){i&&(i.endLine=l,n.push(i)),o=p[1].length,i={name:p[2],kind:"class",startLine:u,endLine:this.findClassEnd(s,l,o),children:[],docstring:this.extractDocstring(s,l+1)};continue}let h=c.match(r.function);if(h){let g=h[1].length,f=h[3],b=i&&g>o,y={name:f,kind:b?"method":"function",startLine:u,endLine:this.findFunctionEnd(s,l,g),docstring:this.extractDocstring(s,l+1)};b&&i?(y.parent=i.name,i.children.push(y)):n.push(y);continue}if(!i&&c.match(r.variable)){let g=c.match(r.variable);g&&n.push({name:g[1],kind:"constant",startLine:u,endLine:u});}}return i&&(i.endLine=s.length,n.push(i)),n}findClassEnd(e,t,s){for(let n=t+1;n<e.length;n++){let r=e[n];if(!r.trim())continue;if((r.match(/^(\s*)/)?.[1].length||0)<=s)return n}return e.length}findFunctionEnd(e,t,s){let n=false;for(let r=t+1;r<e.length;r++){let i=e[r];if(!i.trim())continue;let o=i.match(/^(\s*)/)?.[1].length||0;if(o>s){n=true;continue}if(n&&o<=s)return r}return e.length}extractDocstring(e,t){if(t>=e.length)return;let s=e[t].trim();if(s.startsWith('"""')||s.startsWith("'''")){let n=s.startsWith('"""')?'"""':"'''";if(s.endsWith(n)&&s.length>6)return s.slice(3,-3);let r=[s.slice(3)];for(let i=t+1;i<e.length;i++){let o=e[i].trim();if(o.endsWith(n)){r.push(o.slice(0,-3));break}r.push(o);}return r.join(`
627
627
  `).trim()}}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":case "method":return `(async\\s+)?def\\s+${s}\\s*\\(`;case "class":return `class\\s+${s}(\\s*\\(|\\s*:)`;case "variable":case "constant":return `^${s}\\s*[=:]`;default:return `(def|class)\\s+${s}|^${s}\\s*[=:]`}}};var rr=class{languageId="generic";extensions=["*"];async parse(e,t){let s=e.split(`
628
- `),n=[],r={function:[/^(\s*)(export\s+)?(public\s+|private\s+|protected\s+)?(static\s+)?(async\s+)?(function\s+)?(\w+)\s*\([^)]*\)\s*[:{]/,/^(\s*)func\s+(\w+)\s*\(/,/^(\s*)(pub\s+)?fn\s+(\w+)\s*[<(]/,/^(\s*)(async\s+)?def\s+(\w+)\s*\(/,/^(\s*)def\s+(\w+)/],class:[/^(\s*)(export\s+)?(public\s+|abstract\s+)?(class|struct)\s+(\w+)/,/^(\s*)type\s+(\w+)\s+struct/,/^(\s*)(pub\s+)?struct\s+(\w+)/,/^(\s*)impl\s+(\w+)/],interface:[/^(\s*)(export\s+)?interface\s+(\w+)/,/^(\s*)type\s+(\w+)\s+interface/,/^(\s*)(pub\s+)?trait\s+(\w+)/],constant:[/^(\s*)(export\s+)?(const|final|static\s+final)\s+([A-Z_][A-Z0-9_]*)\s*[=:]/]};for(let i=0;i<s.length;i++){let o=s[i],l=i+1;if(!this.isComment(o)){for(let c of r.function){let u=o.match(c);if(u){let d=this.extractName(u);d&&!this.isKeyword(d)&&n.push({name:d,kind:"function",startLine:l,endLine:Zt(s,i)});break}}for(let c of r.class){let u=o.match(c);if(u){let d=this.extractName(u);d&&n.push({name:d,kind:"class",startLine:l,endLine:Zt(s,i)});break}}for(let c of r.interface){let u=o.match(c);if(u){let d=this.extractName(u);d&&n.push({name:d,kind:"interface",startLine:l,endLine:Zt(s,i)});break}}for(let c of r.constant){let u=o.match(c);if(u){let d=this.extractName(u);d&&n.push({name:d,kind:"constant",startLine:l,endLine:l});break}}}}return n}extractName(e){for(let t=e.length-1;t>0;t--){let s=e[t];if(s&&/^\w+$/.test(s)&&!this.isModifier(s))return s}return null}isModifier(e){return ["public","private","protected","static","final","abstract","async","export","const","let","var","function","class","interface","type","enum","struct","impl","fn","func","def","pub","trait"].includes(e.toLowerCase())}isKeyword(e){return ["if","else","for","while","do","switch","case","break","continue","return","try","catch","finally","throw","new","this","super","null","undefined","true","false","import","from","as","default","with","in","of","get","set","constructor"].includes(e)}isComment(e){let t=e.trim();return t.startsWith("//")||t.startsWith("#")||t.startsWith("/*")||t.startsWith("*")||t.startsWith("--")}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|func|fn|def)\\s+${s}|${s}\\s*\\(`;case "class":return `(class|struct|type)\\s+${s}`;case "interface":return `(interface|trait)\\s+${s}`;default:return `(function|class|interface|struct|type|func|fn|def)\\s+${s}|${s}\\s*[=(]`}}};var ir=class{parsers=new Map;constructor(){this.register(new sr),this.register(new nr),this.register(new rr);}register(e){this.parsers.set(e.languageId,e);for(let t of e.extensions){let s=this.getLanguageFromExtension(t);s&&this.parsers.has(s);}}getParser(e){return this.parsers.has(e)?this.parsers.get(e):e==="javascript"?this.parsers.get("typescript")||null:this.parsers.get("generic")||null}getLanguageFromExtension(e){return {".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".py":"python",".java":"java",".go":"go",".rs":"rust"}[e]||null}getSupportedLanguages(){return Array.from(this.parsers.keys()).filter(e=>e!=="generic")}};var nb="1.0.0",Mi=class{workspacePath;config;metadata=null;fileIndexCache=new Map;parserRegistry;constructor(e,t={}){this.workspacePath=e,this.config={...Gu,...t},this.parserRegistry=new ir;}get indexDir(){return te.join(this.workspacePath,this.config.cacheDir)}async hasIndex(){let e=te.join(this.indexDir,"meta.json");return Wu(e)}async loadMetadata(){if(this.metadata)return this.metadata;let e=te.join(this.indexDir,"meta.json");try{let t=await ce.readFile(e,"utf-8");return this.metadata=JSON.parse(t),this.metadata}catch{return null}}async saveMetadata(){if(!this.metadata)return;await jn(this.indexDir);let e=te.join(this.indexDir,"meta.json");await ce.writeFile(e,JSON.stringify(this.metadata,null,2));}async buildIndex(e={}){let t=Date.now(),s=[],{paths:n=this.config.include,languages:r=this.config.languages,force:i=false,onProgress:o}=e;await jn(this.indexDir),await jn(te.join(this.indexDir,"files"));let l=[];for(let d of n){let p=await on(d,{cwd:this.workspacePath,absolute:true,ignore:this.config.exclude});for(let h of p){let g=Oa(h);g&&r.includes(g)&&l.push(h);}}let c=0,u=0;for(let d=0;d<l.length;d++){let p=l[d];o?.(d+1,l.length,p);try{if(!i){let g=await this.getFileIndex(p);if(g){let f=await ce.stat(p);if(g.mtime>=f.mtimeMs){u+=g.symbols.length,c++;continue}}}let h=await this.indexFile(p);h&&(await this.saveFileIndex(h),this.fileIndexCache.set(p,h),u+=h.symbols.length,c++);}catch(h){s.push({file:p,error:h.message});}}return this.metadata={version:nb,createdAt:this.metadata?.createdAt||Date.now(),updatedAt:Date.now(),fileCount:c,symbolCount:u,languages:r,indexDir:this.config.cacheDir},await this.saveMetadata(),{success:s.length===0,filesIndexed:c,symbolsFound:u,timeMs:Date.now()-t,errors:s}}async indexFile(e){let t=Oa(e);if(!t)return null;let s=this.parserRegistry.getParser(t);if(!s)return null;try{let n=await ce.readFile(e,"utf-8"),r=await ce.stat(e),i=await s.parse(n,e),o=this.extractImports(n,t),l=this.extractExports(n,t);return {path:e,hash:Uu(n),mtime:r.mtimeMs,totalLines:n.split(`
628
+ `),n=[],r={function:[/^(\s*)(export\s+)?(public\s+|private\s+|protected\s+)?(static\s+)?(async\s+)?(function\s+)?(\w+)\s*\([^)]*\)\s*[:{]/,/^(\s*)func\s+(\w+)\s*\(/,/^(\s*)(pub\s+)?fn\s+(\w+)\s*[<(]/,/^(\s*)(async\s+)?def\s+(\w+)\s*\(/,/^(\s*)def\s+(\w+)/],class:[/^(\s*)(export\s+)?(public\s+|abstract\s+)?(class|struct)\s+(\w+)/,/^(\s*)type\s+(\w+)\s+struct/,/^(\s*)(pub\s+)?struct\s+(\w+)/,/^(\s*)impl\s+(\w+)/],interface:[/^(\s*)(export\s+)?interface\s+(\w+)/,/^(\s*)type\s+(\w+)\s+interface/,/^(\s*)(pub\s+)?trait\s+(\w+)/],constant:[/^(\s*)(export\s+)?(const|final|static\s+final)\s+([A-Z_][A-Z0-9_]*)\s*[=:]/]};for(let i=0;i<s.length;i++){let o=s[i],l=i+1;if(!this.isComment(o)){for(let c of r.function){let u=o.match(c);if(u){let d=this.extractName(u);d&&!this.isKeyword(d)&&n.push({name:d,kind:"function",startLine:l,endLine:Zt(s,i)});break}}for(let c of r.class){let u=o.match(c);if(u){let d=this.extractName(u);d&&n.push({name:d,kind:"class",startLine:l,endLine:Zt(s,i)});break}}for(let c of r.interface){let u=o.match(c);if(u){let d=this.extractName(u);d&&n.push({name:d,kind:"interface",startLine:l,endLine:Zt(s,i)});break}}for(let c of r.constant){let u=o.match(c);if(u){let d=this.extractName(u);d&&n.push({name:d,kind:"constant",startLine:l,endLine:l});break}}}}return n}extractName(e){for(let t=e.length-1;t>0;t--){let s=e[t];if(s&&/^\w+$/.test(s)&&!this.isModifier(s))return s}return null}isModifier(e){return ["public","private","protected","static","final","abstract","async","export","const","let","var","function","class","interface","type","enum","struct","impl","fn","func","def","pub","trait"].includes(e.toLowerCase())}isKeyword(e){return ["if","else","for","while","do","switch","case","break","continue","return","try","catch","finally","throw","new","this","super","null","undefined","true","false","import","from","as","default","with","in","of","get","set","constructor"].includes(e)}isComment(e){let t=e.trim();return t.startsWith("//")||t.startsWith("#")||t.startsWith("/*")||t.startsWith("*")||t.startsWith("--")}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|func|fn|def)\\s+${s}|${s}\\s*\\(`;case "class":return `(class|struct|type)\\s+${s}`;case "interface":return `(interface|trait)\\s+${s}`;default:return `(function|class|interface|struct|type|func|fn|def)\\s+${s}|${s}\\s*[=(]`}}};var ir=class{parsers=new Map;constructor(){this.register(new sr),this.register(new nr),this.register(new rr);}register(e){this.parsers.set(e.languageId,e);for(let t of e.extensions){let s=this.getLanguageFromExtension(t);s&&this.parsers.has(s);}}getParser(e){return this.parsers.has(e)?this.parsers.get(e):e==="javascript"?this.parsers.get("typescript")||null:this.parsers.get("generic")||null}getLanguageFromExtension(e){return {".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".py":"python",".java":"java",".go":"go",".rs":"rust"}[e]||null}getSupportedLanguages(){return Array.from(this.parsers.keys()).filter(e=>e!=="generic")}};var rb="1.0.0",Mi=class{workspacePath;config;metadata=null;fileIndexCache=new Map;parserRegistry;constructor(e,t={}){this.workspacePath=e,this.config={...Gu,...t},this.parserRegistry=new ir;}get indexDir(){return te.join(this.workspacePath,this.config.cacheDir)}async hasIndex(){let e=te.join(this.indexDir,"meta.json");return Wu(e)}async loadMetadata(){if(this.metadata)return this.metadata;let e=te.join(this.indexDir,"meta.json");try{let t=await ce.readFile(e,"utf-8");return this.metadata=JSON.parse(t),this.metadata}catch{return null}}async saveMetadata(){if(!this.metadata)return;await jn(this.indexDir);let e=te.join(this.indexDir,"meta.json");await ce.writeFile(e,JSON.stringify(this.metadata,null,2));}async buildIndex(e={}){let t=Date.now(),s=[],{paths:n=this.config.include,languages:r=this.config.languages,force:i=false,onProgress:o}=e;await jn(this.indexDir),await jn(te.join(this.indexDir,"files"));let l=[];for(let d of n){let p=await on(d,{cwd:this.workspacePath,absolute:true,ignore:this.config.exclude});for(let h of p){let g=Oa(h);g&&r.includes(g)&&l.push(h);}}let c=0,u=0;for(let d=0;d<l.length;d++){let p=l[d];o?.(d+1,l.length,p);try{if(!i){let g=await this.getFileIndex(p);if(g){let f=await ce.stat(p);if(g.mtime>=f.mtimeMs){u+=g.symbols.length,c++;continue}}}let h=await this.indexFile(p);h&&(await this.saveFileIndex(h),this.fileIndexCache.set(p,h),u+=h.symbols.length,c++);}catch(h){s.push({file:p,error:h.message});}}return this.metadata={version:rb,createdAt:this.metadata?.createdAt||Date.now(),updatedAt:Date.now(),fileCount:c,symbolCount:u,languages:r,indexDir:this.config.cacheDir},await this.saveMetadata(),{success:s.length===0,filesIndexed:c,symbolsFound:u,timeMs:Date.now()-t,errors:s}}async indexFile(e){let t=Oa(e);if(!t)return null;let s=this.parserRegistry.getParser(t);if(!s)return null;try{let n=await ce.readFile(e,"utf-8"),r=await ce.stat(e),i=await s.parse(n,e),o=this.extractImports(n,t),l=this.extractExports(n,t);return {path:e,hash:Uu(n),mtime:r.mtimeMs,totalLines:n.split(`
629
629
  `).length,symbols:i,imports:o,exports:l}}catch{return null}}extractImports(e,t){let s=[],n=e.split(`
630
630
  `);if(["typescript","javascript"].includes(t)){let r=/^import\s+(?:(?:\{([^}]+)\}|(\w+))\s+from\s+)?['"]([^'"]+)['"]/;n.forEach((i,o)=>{let l=i.match(r);if(l){let c=l[1]?.split(",").map(u=>u.trim())||(l[2]?[l[2]]:[]);s.push({module:l[3],line:o+1,names:c.filter(Boolean)});}});}if(t==="python"){let r=/^(?:from\s+(\S+)\s+import\s+(.+)|import\s+(\S+))/;n.forEach((i,o)=>{let l=i.match(r);if(l){let c=l[1]||l[3],u=l[2]?.split(",").map(d=>d.trim())||[];s.push({module:c,line:o+1,names:u});}});}return s}extractExports(e,t){let s=[],n=e.split(`
631
- `);if(["typescript","javascript"].includes(t)){let r=/^export\s+(?:(default)\s+)?(?:(class|function|const|let|var|interface|type|enum)\s+)?(\w+)?/;n.forEach((i,o)=>{let l=i.match(r);if(l){let c=l[2],u=l[3]||(l[1]?"default":"");u&&s.push({name:u,line:o+1,kind:c});}});}return s}async getFileIndex(e){if(this.fileIndexCache.has(e))return this.fileIndexCache.get(e);let t=this.getFileIndexPath(e);try{let s=await ce.readFile(t,"utf-8"),n=JSON.parse(s);return this.fileIndexCache.set(e,n),n}catch{return null}}async saveFileIndex(e){let t=this.getFileIndexPath(e.path);await jn(te.dirname(t)),await ce.writeFile(t,JSON.stringify(e,null,2));}getFileIndexPath(e){let s=te.relative(this.workspacePath,e).replace(/[/\\]/g,"_").replace(/\./g,"_");return te.join(this.indexDir,"files",`${s}.json`)}async searchSymbol(e){let{query:t,kind:s,fuzzy:n=false,limit:r=20}=e,i=[],o=te.join(this.indexDir,"files");try{let l=await ce.readdir(o);for(let c of l)if(c.endsWith(".json"))try{let u=await ce.readFile(te.join(o,c),"utf-8"),d=JSON.parse(u);for(let p of d.symbols){if(s&&p.kind!==s)continue;let h=0;if(n){if(h=Na(t.toLowerCase(),p.name.toLowerCase()),h<.5)continue}else {if(!p.name.toLowerCase().includes(t.toLowerCase()))continue;h=p.name.toLowerCase()===t.toLowerCase()?1:.8;}if(i.push({symbol:p,file:d.path,score:h}),p.children)for(let g of p.children){if(s&&g.kind!==s)continue;let f=0;if(n){if(f=Na(t.toLowerCase(),g.name.toLowerCase()),f<.5)continue}else {if(!g.name.toLowerCase().includes(t.toLowerCase()))continue;f=g.name.toLowerCase()===t.toLowerCase()?1:.8;}i.push({symbol:{...g,parent:p.name},file:d.path,score:f});}}}catch{continue}}catch{}return i.sort((l,c)=>c.score-l.score).slice(0,r)}async invalidate(e){this.fileIndexCache.delete(e);let t=this.getFileIndexPath(e);try{await ce.unlink(t);}catch{}}async clear(){this.fileIndexCache.clear(),this.metadata=null;try{await ce.rm(this.indexDir,{recursive:!0,force:!0});}catch{}}async getStats(){let e=await this.loadMetadata();if(!e)return {hasIndex:false,fileCount:0,symbolCount:0,lastUpdated:null,size:0};let t=0;try{let s=te.join(this.indexDir,"files"),n=await ce.readdir(s);for(let r of n){let i=await ce.stat(te.join(s,r));t+=i.size;}}catch{}return {hasIndex:true,fileCount:e.fileCount,symbolCount:e.symbolCount,lastUpdated:new Date(e.updatedAt),size:t}}};function rl(a,e){return new Mi(a,e)}var an=null,ln=null,Di=null,Ss={small:qs,large:1e3},Ud=12e3,rb=120,Pi=20,ib=3,ob=200,il=200;function ab(a){return (!an||Di!==a)&&(an=$a(a),Di=a,ln&&an.setIndexManager(ln)),an}function or(a){return (!ln||Di!==a)&&(ln=rl(a),Di=a,an&&an.setIndexManager(ln)),ln}function lb(a){return process.cwd()}function Dt(a){let e=lb();return te.relative(e,a)||a}function Wd(a,e){let t=te.relative(a,e);return t===""?true:!t.startsWith("..")&&!te.isAbsolute(t)}function cb(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ol(a){let e=a||process.cwd(),s=await or(e).getStats();return {hasIndex:s.hasIndex,fileCount:s.fileCount,symbolCount:s.symbolCount,lastUpdated:s.lastUpdated}}async function qd(a){let e=await ol(a);return e.hasIndex?`
631
+ `);if(["typescript","javascript"].includes(t)){let r=/^export\s+(?:(default)\s+)?(?:(class|function|const|let|var|interface|type|enum)\s+)?(\w+)?/;n.forEach((i,o)=>{let l=i.match(r);if(l){let c=l[2],u=l[3]||(l[1]?"default":"");u&&s.push({name:u,line:o+1,kind:c});}});}return s}async getFileIndex(e){if(this.fileIndexCache.has(e))return this.fileIndexCache.get(e);let t=this.getFileIndexPath(e);try{let s=await ce.readFile(t,"utf-8"),n=JSON.parse(s);return this.fileIndexCache.set(e,n),n}catch{return null}}async saveFileIndex(e){let t=this.getFileIndexPath(e.path);await jn(te.dirname(t)),await ce.writeFile(t,JSON.stringify(e,null,2));}getFileIndexPath(e){let s=te.relative(this.workspacePath,e).replace(/[/\\]/g,"_").replace(/\./g,"_");return te.join(this.indexDir,"files",`${s}.json`)}async searchSymbol(e){let{query:t,kind:s,fuzzy:n=false,limit:r=20}=e,i=[],o=te.join(this.indexDir,"files");try{let l=await ce.readdir(o);for(let c of l)if(c.endsWith(".json"))try{let u=await ce.readFile(te.join(o,c),"utf-8"),d=JSON.parse(u);for(let p of d.symbols){if(s&&p.kind!==s)continue;let h=0;if(n){if(h=Na(t.toLowerCase(),p.name.toLowerCase()),h<.5)continue}else {if(!p.name.toLowerCase().includes(t.toLowerCase()))continue;h=p.name.toLowerCase()===t.toLowerCase()?1:.8;}if(i.push({symbol:p,file:d.path,score:h}),p.children)for(let g of p.children){if(s&&g.kind!==s)continue;let f=0;if(n){if(f=Na(t.toLowerCase(),g.name.toLowerCase()),f<.5)continue}else {if(!g.name.toLowerCase().includes(t.toLowerCase()))continue;f=g.name.toLowerCase()===t.toLowerCase()?1:.8;}i.push({symbol:{...g,parent:p.name},file:d.path,score:f});}}}catch{continue}}catch{}return i.sort((l,c)=>c.score-l.score).slice(0,r)}async invalidate(e){this.fileIndexCache.delete(e);let t=this.getFileIndexPath(e);try{await ce.unlink(t);}catch{}}async clear(){this.fileIndexCache.clear(),this.metadata=null;try{await ce.rm(this.indexDir,{recursive:!0,force:!0});}catch{}}async getStats(){let e=await this.loadMetadata();if(!e)return {hasIndex:false,fileCount:0,symbolCount:0,lastUpdated:null,size:0};let t=0;try{let s=te.join(this.indexDir,"files"),n=await ce.readdir(s);for(let r of n){let i=await ce.stat(te.join(s,r));t+=i.size;}}catch{}return {hasIndex:true,fileCount:e.fileCount,symbolCount:e.symbolCount,lastUpdated:new Date(e.updatedAt),size:t}}};function rl(a,e){return new Mi(a,e)}var an=null,ln=null,Di=null,Ss={small:qs,large:1e3},Ud=12e3,ib=120,Pi=20,ob=3,ab=200,il=200;function lb(a){return (!an||Di!==a)&&(an=$a(a),Di=a,ln&&an.setIndexManager(ln)),an}function or(a){return (!ln||Di!==a)&&(ln=rl(a),Di=a,an&&an.setIndexManager(ln)),ln}function cb(a){return process.cwd()}function Dt(a){let e=cb();return te.relative(e,a)||a}function Wd(a,e){let t=te.relative(a,e);return t===""?true:!t.startsWith("..")&&!te.isAbsolute(t)}function ub(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ol(a){let e=a||process.cwd(),s=await or(e).getStats();return {hasIndex:s.hasIndex,fileCount:s.fileCount,symbolCount:s.symbolCount,lastUpdated:s.lastUpdated}}async function qd(a){let e=await ol(a);return e.hasIndex?`
632
632
  \u{1F4D6} readfile \u7B56\u7565\u63D0\u793A (\u7D22\u5F15\u5DF2\u542F\u7528, ${e.symbolCount} \u7B26\u53F7):
633
633
  - \u5C0F\u6587\u4EF6 (\u2264${Ss.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
634
634
  - \u5927\u6587\u4EF6 (>${Ss.large}\u884C): \u4F18\u5148\u7528 symbol/function/class \u5B9A\u4F4D
@@ -684,9 +684,9 @@ readfile(path="src/main.ts", range_start="// BEGIN CONFIG", range_end="// END CO
684
684
  - \u{1F525} edit_file \u524D\u5FC5\u987B\u5148 readfile(..., for_edit=true) - old_string \u987B\u4ECE\u8F93\u51FA\u7CBE\u786E\u590D\u5236
685
685
  - for_edit=true \u4F1A\u5305\u542B COPY \u533A\u5757\uFF08\u8F93\u51FA\u66F4\u5927\uFF09
686
686
  - max_output_chars \u53EF\u9650\u5236\u8F93\u51FA\u957F\u5EA6
687
- - \u652F\u6301 TypeScript/JavaScript/Python/Java \u7B49\u591A\u79CD\u8BED\u8A00`,parameters:{type:"object",properties:{path:{type:"string",description:"\u6587\u4EF6\u8DEF\u5F84 (\u5FC5\u9700)"},start_line:{type:"number",description:"\u8D77\u59CB\u884C\u53F7 (1-indexed)"},end_line:{type:"number",description:"\u7ED3\u675F\u884C\u53F7"},num_lines:{type:"number",description:`\u8BFB\u53D6\u884C\u6570 (\u9ED8\u8BA4: ${$n})`},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u51FD\u6570\u540D\u3001\u7C7B\u540D\u3001\u53D8\u91CF\u540D\u7B49)"},symbol_kind:{type:"string",description:"\u7B26\u53F7\u7C7B\u578B: function, class, interface, method, variable, type, enum",enum:["function","class","interface","method","variable","type","enum"]},class_name:{type:"string",description:"\u6240\u5C5E\u7C7B\u540D (\u7528\u4E8E\u5B9A\u4F4D\u7C7B\u7684\u65B9\u6CD5)"},function:{type:"string",description:"\u51FD\u6570\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=function)"},class:{type:"string",description:"\u7C7B\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=class)"},pattern:{type:"string",description:"\u641C\u7D22\u6A21\u5F0F (\u6B63\u5219\u8868\u8FBE\u5F0F)"},match_index:{type:"number",description:"\u5339\u914D\u7B2C\u51E0\u4E2A\u7ED3\u679C (\u9ED8\u8BA4: 1)"},list_matches:{type:"boolean",description:"\u4EC5\u5217\u51FA\u5339\u914D\u884C\u6458\u8981 (\u9ED8\u8BA4: false, \u9700\u914D\u5408 pattern)"},range_start:{type:"string",description:"\u8303\u56F4\u5F00\u59CB\u6A21\u5F0F"},range_end:{type:"string",description:"\u8303\u56F4\u7ED3\u675F\u6A21\u5F0F"},ranges:{type:"array",items:{type:"object",properties:{start:{type:"number"},end:{type:"number"}},required:["start"]},description:'\u591A\u4E2A\u884C\u8303\u56F4\u6279\u91CF\u8BFB\u53D6 (e.g., [{"start":10,"end":120},{"start":300,"end":480}])'},anchor_lines:{type:"array",items:{type:"number"},description:"\u6309\u884C\u53F7\u6279\u91CF\u8BFB\u53D6 (\u4F1A\u4EE5\u884C\u53F7\u4E3A\u4E2D\u5FC3\u5C55\u5F00 num_lines \u6216 context)"},context:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 10)"},use_index:{type:"boolean",description:"\u662F\u5426\u4F7F\u7528\u7D22\u5F15 (\u9ED8\u8BA4: true, \u5982\u679C\u7D22\u5F15\u53EF\u7528)"},for_edit:{type:"boolean",description:"\u662F\u5426\u5305\u542B edit_file \u53EF\u590D\u5236\u7684\u539F\u59CB\u5185\u5BB9\u5757 (\u9ED8\u8BA4: false)"},max_output_chars:{type:"number",description:`\u6700\u5927\u8F93\u51FA\u5B57\u7B26\u6570 (\u9ED8\u8BA4: ${Ud})`},read_all:{type:"boolean",description:"\u4E00\u6B21\u6027\u8BFB\u53D6\u6574\u4E2A\u6587\u4EF6 (\u5FFD\u7565 num_lines \u9650\u5236\uFF0C\u9002\u7528\u4E8E\u5C0F\u6587\u4EF6\u5982 SKILL.md)"}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:d,num_lines:p,symbol:h,symbol_kind:g,class_name:f,function:b,class:y,pattern:w,match_index:C,list_matches:k,range_start:T,range_end:_,ranges:M,anchor_lines:F,context:x,use_index:R=true,for_edit:j,max_output_chars:v,read_all:E}=l,L=e(),I=ab(L),A=j===true,O=typeof x=="number"?Math.max(0,x):ui,$=typeof v=="number"&&v>0?Math.floor(v):Ud,P=E?Fn:p||(A?rb:$n);P=Math.min(P,Fn),!p&&w&&(P=Math.max(Pi,O*2+1));let N=Array.isArray(M)&&M.length>0,D=Array.isArray(F)&&F.length>0,G=k===true;if(A&&(N||D||G))return "\u2717 for_edit=true \u6682\u4E0D\u652F\u6301 list_matches / ranges / anchor_lines\uFF0C\u8BF7\u4F7F\u7528\u5355\u6B21 readfile \u83B7\u53D6\u53EF\u7F16\u8F91\u7247\u6BB5\u3002";let q=()=>te.isAbsolute(c)?c:te.resolve(L,c),oe=async()=>{let ee=q(),fe=await ce.readFile(ee,"utf-8"),le=Ks(fe).split(`
687
+ - \u652F\u6301 TypeScript/JavaScript/Python/Java \u7B49\u591A\u79CD\u8BED\u8A00`,parameters:{type:"object",properties:{path:{type:"string",description:"\u6587\u4EF6\u8DEF\u5F84 (\u5FC5\u9700)"},start_line:{type:"number",description:"\u8D77\u59CB\u884C\u53F7 (1-indexed)"},end_line:{type:"number",description:"\u7ED3\u675F\u884C\u53F7"},num_lines:{type:"number",description:`\u8BFB\u53D6\u884C\u6570 (\u9ED8\u8BA4: ${$n})`},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u51FD\u6570\u540D\u3001\u7C7B\u540D\u3001\u53D8\u91CF\u540D\u7B49)"},symbol_kind:{type:"string",description:"\u7B26\u53F7\u7C7B\u578B: function, class, interface, method, variable, type, enum",enum:["function","class","interface","method","variable","type","enum"]},class_name:{type:"string",description:"\u6240\u5C5E\u7C7B\u540D (\u7528\u4E8E\u5B9A\u4F4D\u7C7B\u7684\u65B9\u6CD5)"},function:{type:"string",description:"\u51FD\u6570\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=function)"},class:{type:"string",description:"\u7C7B\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=class)"},pattern:{type:"string",description:"\u641C\u7D22\u6A21\u5F0F (\u6B63\u5219\u8868\u8FBE\u5F0F)"},match_index:{type:"number",description:"\u5339\u914D\u7B2C\u51E0\u4E2A\u7ED3\u679C (\u9ED8\u8BA4: 1)"},list_matches:{type:"boolean",description:"\u4EC5\u5217\u51FA\u5339\u914D\u884C\u6458\u8981 (\u9ED8\u8BA4: false, \u9700\u914D\u5408 pattern)"},range_start:{type:"string",description:"\u8303\u56F4\u5F00\u59CB\u6A21\u5F0F"},range_end:{type:"string",description:"\u8303\u56F4\u7ED3\u675F\u6A21\u5F0F"},ranges:{type:"array",items:{type:"object",properties:{start:{type:"number"},end:{type:"number"}},required:["start"]},description:'\u591A\u4E2A\u884C\u8303\u56F4\u6279\u91CF\u8BFB\u53D6 (e.g., [{"start":10,"end":120},{"start":300,"end":480}])'},anchor_lines:{type:"array",items:{type:"number"},description:"\u6309\u884C\u53F7\u6279\u91CF\u8BFB\u53D6 (\u4F1A\u4EE5\u884C\u53F7\u4E3A\u4E2D\u5FC3\u5C55\u5F00 num_lines \u6216 context)"},context:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 10)"},use_index:{type:"boolean",description:"\u662F\u5426\u4F7F\u7528\u7D22\u5F15 (\u9ED8\u8BA4: true, \u5982\u679C\u7D22\u5F15\u53EF\u7528)"},for_edit:{type:"boolean",description:"\u662F\u5426\u5305\u542B edit_file \u53EF\u590D\u5236\u7684\u539F\u59CB\u5185\u5BB9\u5757 (\u9ED8\u8BA4: false)"},max_output_chars:{type:"number",description:`\u6700\u5927\u8F93\u51FA\u5B57\u7B26\u6570 (\u9ED8\u8BA4: ${Ud})`},read_all:{type:"boolean",description:"\u4E00\u6B21\u6027\u8BFB\u53D6\u6574\u4E2A\u6587\u4EF6 (\u5FFD\u7565 num_lines \u9650\u5236\uFF0C\u9002\u7528\u4E8E\u5C0F\u6587\u4EF6\u5982 SKILL.md)"}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:d,num_lines:p,symbol:h,symbol_kind:g,class_name:f,function:b,class:y,pattern:w,match_index:C,list_matches:k,range_start:T,range_end:_,ranges:M,anchor_lines:F,context:x,use_index:R=true,for_edit:j,max_output_chars:v,read_all:E}=l,L=e(),I=lb(L),A=j===true,O=typeof x=="number"?Math.max(0,x):ui,$=typeof v=="number"&&v>0?Math.floor(v):Ud,P=E?Fn:p||(A?ib:$n);P=Math.min(P,Fn),!p&&w&&(P=Math.max(Pi,O*2+1));let N=Array.isArray(M)&&M.length>0,D=Array.isArray(F)&&F.length>0,G=k===true;if(A&&(N||D||G))return "\u2717 for_edit=true \u6682\u4E0D\u652F\u6301 list_matches / ranges / anchor_lines\uFF0C\u8BF7\u4F7F\u7528\u5355\u6B21 readfile \u83B7\u53D6\u53EF\u7F16\u8F91\u7247\u6BB5\u3002";let q=()=>te.isAbsolute(c)?c:te.resolve(L,c),oe=async()=>{let ee=q(),fe=await ce.readFile(ee,"utf-8"),le=Ks(fe).split(`
688
688
  `);return {absPath:ee,lines:le,totalLines:le.length}},ue=(ee,fe,ne)=>{let le=Math.max(1,Math.floor(ee)),Q=typeof fe=="number"?Math.floor(fe):le+P-1,Be=Math.min(ne,Math.max(Q,le));return {start:le,end:Be}},Se=ee=>{let fe=ee.filter(le=>Number.isFinite(le.start)&&Number.isFinite(le.end)).sort((le,Q)=>le.start-Q.start),ne=[];for(let le of fe){let Q=ne[ne.length-1];!Q||le.start>Q.end+1?ne.push({...le}):Q.end=Math.max(Q.end,le.end);}return ne};if(G){if(!w)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:ee,lines:fe,totalLines:ne}=await oe(),le;try{le=new RegExp(w,"gi");}catch(ae){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${ae.message}`}let Q=[];fe.forEach((ae,S)=>{le.test(ae)&&Q.push({line:S+1,text:ae}),le.lastIndex=0;});let Be=Dt(ee);if(Q.length===0){let ae=ze(fe.slice(0,Math.min(50,ne)),1);return [`\u2713 \u6587\u4EF6: ${Be}`,`\u603B\u884C\u6570: ${ne} | \u5339\u914D: 0`,"\u7B56\u7565: grep-list","",`\u672A\u627E\u5230\u5339\u914D: "${w}"`,"","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---",ae].join(`
689
- `)}let qe=il+12,B=Math.max(5,Math.min(ob,Math.floor($/qe))),re=Q.slice(0,B),V=re.map(ae=>{let S=ae.text.length>il?`${ae.text.slice(0,il)}...`:ae.text;return `${String(ae.line).padStart(6)} \u2502 ${S}`}),pe=[`\u2713 \u6587\u4EF6: ${Be}`,`\u603B\u884C\u6570: ${ne} | \u5339\u914D: ${Q.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${V.length}/${Q.length}\uFF09---`,...V];V.length<Q.length&&pe.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let Re=re.slice(0,5).map(ae=>ae.line).join(", ");return pe.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${Be}", anchor_lines=[${Re}], num_lines=${Math.min(200,P)})`),pe.join(`
689
+ `)}let qe=il+12,B=Math.max(5,Math.min(ab,Math.floor($/qe))),re=Q.slice(0,B),V=re.map(ae=>{let S=ae.text.length>il?`${ae.text.slice(0,il)}...`:ae.text;return `${String(ae.line).padStart(6)} \u2502 ${S}`}),pe=[`\u2713 \u6587\u4EF6: ${Be}`,`\u603B\u884C\u6570: ${ne} | \u5339\u914D: ${Q.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${V.length}/${Q.length}\uFF09---`,...V];V.length<Q.length&&pe.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let Re=re.slice(0,5).map(ae=>ae.line).join(", ");return pe.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${Be}", anchor_lines=[${Re}], num_lines=${Math.min(200,P)})`),pe.join(`
690
690
  `)}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}}if(N||D)try{let{absPath:ee,lines:fe,totalLines:ne}=await oe(),le=[];if(N)for(let V of M)!V||typeof V.start!="number"||le.push(ue(V.start,V.end,ne));else if(D){let V=Math.max(1,p||O*2+1);for(let pe of F){if(typeof pe!="number"||Number.isNaN(pe))continue;let Re=Math.max(1,Math.floor(pe-Math.floor(V/2))),ae=Math.min(ne,Re+V-1);le.push({start:Re,end:ae});}}if(le.length===0)return "\u2717 ranges/anchor_lines \u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8BFB\u53D6";let Q=Se(le),qe=[`\u2713 \u6587\u4EF6: ${Dt(ee)}`,`\u603B\u884C\u6570: ${ne} | \u533A\u5757: ${Q.length}`,"\u7B56\u7565: batch-range","","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"],B=qe.join(`
691
691
  `).length,re=0;for(let[V,pe]of Q.entries()){let Re=ze(fe.slice(pe.start-1,pe.end),pe.start),S=`${`# \u533A\u5757 ${V+1}: ${pe.start}-${pe.end}`}
692
692
  ${Re}`;if(B+S.length+2>$&&re>0)break;qe.push(S,""),B+=S.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(`
@@ -701,7 +701,7 @@ ${Re}`;if(B+S.length+2>$&&re>0)break;qe.push(S,""),B+=S.length+2,re+=1;}return r
701
701
 
702
702
  \u{1F4A1} \u5EFA\u8BAE:
703
703
  - \u4F7F\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
704
- - \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),xe&&ee.strategy==="full"&&K.length>$){xe=false;let le=Math.max(.1,Math.min(.9,$/K.length));P=Math.max(Pi,Math.floor(P*le)),ie+=1;continue}if(p||K.length<=$||ie>=ib||P<=Pi)return K;let fe=Math.max(.1,Math.min(.9,$/K.length)),ne=Math.max(Pi,Math.floor(P*fe));if(ne>=P)return K;P=ne,ie+=1;}}},s={name:"build_index",description:`\u3010\u6784\u5EFA\u4EE3\u7801\u7D22\u5F15\u3011\u4E3A\u9879\u76EE\u6784\u5EFA AST \u7D22\u5F15\uFF0C\u63D0\u5347\u4EE3\u7801\u5BFC\u822A\u901F\u5EA6\u3002
704
+ - \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),xe&&ee.strategy==="full"&&K.length>$){xe=false;let le=Math.max(.1,Math.min(.9,$/K.length));P=Math.max(Pi,Math.floor(P*le)),ie+=1;continue}if(p||K.length<=$||ie>=ob||P<=Pi)return K;let fe=Math.max(.1,Math.min(.9,$/K.length)),ne=Math.max(Pi,Math.floor(P*fe));if(ne>=P)return K;P=ne,ie+=1;}}},s={name:"build_index",description:`\u3010\u6784\u5EFA\u4EE3\u7801\u7D22\u5F15\u3011\u4E3A\u9879\u76EE\u6784\u5EFA AST \u7D22\u5F15\uFF0C\u63D0\u5347\u4EE3\u7801\u5BFC\u822A\u901F\u5EA6\u3002
705
705
 
706
706
  \u26A1 \u7279\u6027:
707
707
  - \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
  \u793A\u4F8B:
765
765
  get_references(query="UserService")
766
766
  get_references(symbol="handleLogin", path="src/auth")
767
- get_references(query="FeatureFlag", file_pattern="*.ts")`,parameters:{type:"object",properties:{query:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u4F18\u5148)"},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (query \u7684\u522B\u540D)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u76F8\u5BF9\u5DE5\u4F5C\u533A\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u533A)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,ts}")'},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: false)"},regex:{type:"boolean",description:"\u5C06 query \u4F5C\u4E3A\u6B63\u5219 (\u9ED8\u8BA4: false)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"}}},permission:{category:"read",allowInAskMode:true},async function(l){let c=typeof l.query=="string"?l.query:typeof l.symbol=="string"?l.symbol:"";if(!c.trim())return "\u2717 \u7F3A\u5C11\u53C2\u6570: query (\u6216 symbol)";let u=e(),d=te.resolve(u,l.path||".");if(!Wd(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:cb(c);y=new RegExp(x,f?"gi":"g");}catch(x){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${x.message}`}let w=[];if(p.isDirectory()){let x=l.file_pattern||"**/*";w=await on(x,{cwd:d,absolute:true,nodir:true,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.next/**","**/coverage/**","**/__pycache__/**","**/target/**","**/vendor/**"]});}else w=[d];if(w.length===0)return "\u2713 \u672A\u627E\u5230\u53EF\u641C\u7D22\u7684\u6587\u4EF6";let C=[],k=0,T=0,_=0;for(let x of w){if(k>=g)break;try{let R=await ce.readFile(x,"utf-8");if(R.includes("\0"))continue;let j=R.split(`
767
+ get_references(query="FeatureFlag", file_pattern="*.ts")`,parameters:{type:"object",properties:{query:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u4F18\u5148)"},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (query \u7684\u522B\u540D)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u76F8\u5BF9\u5DE5\u4F5C\u533A\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u533A)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,ts}")'},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: false)"},regex:{type:"boolean",description:"\u5C06 query \u4F5C\u4E3A\u6B63\u5219 (\u9ED8\u8BA4: false)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"}}},permission:{category:"read",allowInAskMode:true},async function(l){let c=typeof l.query=="string"?l.query:typeof l.symbol=="string"?l.symbol:"";if(!c.trim())return "\u2717 \u7F3A\u5C11\u53C2\u6570: query (\u6216 symbol)";let u=e(),d=te.resolve(u,l.path||".");if(!Wd(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:ub(c);y=new RegExp(x,f?"gi":"g");}catch(x){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${x.message}`}let w=[];if(p.isDirectory()){let x=l.file_pattern||"**/*";w=await on(x,{cwd:d,absolute:true,nodir:true,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.next/**","**/coverage/**","**/__pycache__/**","**/target/**","**/vendor/**"]});}else w=[d];if(w.length===0)return "\u2713 \u672A\u627E\u5230\u53EF\u641C\u7D22\u7684\u6587\u4EF6";let C=[],k=0,T=0,_=0;for(let x of w){if(k>=g)break;try{let R=await ce.readFile(x,"utf-8");if(R.includes("\0"))continue;let j=R.split(`
768
768
  `),v=new Set,E=new Map;for(let L=0;L<j.length&&!(k>=g);L++){let I=j[L],A=y.test(I);if(y.lastIndex=0,A){v.add(L),k++;let O=Math.max(0,L-h),$=Math.min(j.length-1,L+h);for(let P=O;P<=$;P++){let N=E.get(P);E.set(P,{line:j[P],isMatch:N?.isMatch||P===L});}}}if(T++,v.size>0){_++;let I=Array.from(E.keys()).sort((A,O)=>A-O).map(A=>({lineNum:A+1,line:E.get(A)?.line||"",isMatch:E.get(A)?.isMatch||!1}));C.push({file:x,matches:I,matchCount:v.size});}}catch{continue}}let M=Dt(d),F=[`\u2713 \u5F15\u7528: "${c}"`,`\u25B8 \u8DEF\u5F84: ${M}`,l.file_pattern?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l.file_pattern}`:"",f?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",b?"\u25B8 \u6A21\u5F0F: \u6B63\u5219":"","",`\u6587\u4EF6: ${T} \u5DF2\u641C\u7D22, ${_} \u6709\u5339\u914D`,`\u5339\u914D: ${k}${k>=g?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(x=>x!=="");for(let x of C){let R=Dt(x.file);F.push(`
769
769
  \u25B8 ${R} (${x.matchCount} \u5904)`),F.push("\u2500".repeat(50));let j=-10;for(let v of x.matches){v.lineNum>j+1&&j>0&&F.push(" \u2504\u2504\u2504");let E=v.isMatch?"\u25B6":" ";F.push(`${E}${String(v.lineNum).padStart(5)} \u2502 ${v.line}`),j=v.lineNum;}}return C.length===0&&(F.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),F.push(""),F.push("\u{1F4A1} \u5EFA\u8BAE:"),F.push(" - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199"),F.push(" - \u4F7F\u7528 regex=true \u8FDB\u884C\u66F4\u7CBE\u786E\u5339\u914D"),F.push(" - \u7F29\u5C0F\u6216\u6269\u5927 path/file_pattern \u8303\u56F4")),F.join(`
770
770
  `)}};return [t,s,n,r,i,{name:"index_stats",description:"\u3010\u7D22\u5F15\u7EDF\u8BA1\u3011\u67E5\u770B\u5F53\u524D\u9879\u76EE\u7684\u7D22\u5F15\u72B6\u6001\u548C\u7EDF\u8BA1\u4FE1\u606F\u3002",parameters:{type:"object",properties:{}},async function(){let l=e(),u=await or(l).getStats();if(!u.hasIndex)return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u672A\u6784\u5EFA
@@ -786,7 +786,7 @@ Rules:
786
786
  - Keep step descriptions short (5-7 words)
787
787
  - Only ONE step should be "in_progress" at any time
788
788
  - Mark completed steps as "completed"
789
- - Update the plan whenever you complete a step or start a new one`,parameters:{type:"object",properties:{explanation:{type:"string",description:"Optional explanation for the plan update"},plan:{type:"array",description:"The list of steps",items:{type:"object",properties:{step:{type:"string",description:"Step description (5-7 words)"},status:{type:"string",enum:["pending","in_progress","completed"],description:"Step status: pending, in_progress, or completed"}},required:["step","status"]}}},required:["plan"]}};function zd(a){return a.plan.filter(t=>t.status==="in_progress").length>1?JSON.stringify({success:false,error:"At most one step can be in_progress at a time"}):JSON.stringify({success:true,message:"Plan updated"})}var lr=new Map,cr=null;var ub=0,Jd={name:"ask_user",description:`\u5411\u7528\u6237\u63D0\u95EE\u5E76\u7B49\u5F85\u56DE\u7B54\u3002\u7528\u4E8E\u9700\u8981\u7528\u6237\u786E\u8BA4\u3001\u9009\u62E9\u65B9\u6848\u6216\u63D0\u4F9B\u504F\u597D\u65F6\u3002
789
+ - Update the plan whenever you complete a step or start a new one`,parameters:{type:"object",properties:{explanation:{type:"string",description:"Optional explanation for the plan update"},plan:{type:"array",description:"The list of steps",items:{type:"object",properties:{step:{type:"string",description:"Step description (5-7 words)"},status:{type:"string",enum:["pending","in_progress","completed"],description:"Step status: pending, in_progress, or completed"}},required:["step","status"]}}},required:["plan"]}};function zd(a){return a.plan.filter(t=>t.status==="in_progress").length>1?JSON.stringify({success:false,error:"At most one step can be in_progress at a time"}):JSON.stringify({success:true,message:"Plan updated"})}var lr=new Map,cr=null;var db=0,Jd={name:"ask_user",description:`\u5411\u7528\u6237\u63D0\u95EE\u5E76\u7B49\u5F85\u56DE\u7B54\u3002\u7528\u4E8E\u9700\u8981\u7528\u6237\u786E\u8BA4\u3001\u9009\u62E9\u65B9\u6848\u6216\u63D0\u4F9B\u504F\u597D\u65F6\u3002
790
790
 
791
791
  \u4F55\u65F6\u4F7F\u7528\uFF1A
792
792
  - \u9700\u8981\u7528\u6237\u5728\u591A\u4E2A\u65B9\u6848\u4E2D\u9009\u62E9
@@ -795,8 +795,8 @@ Rules:
795
795
 
796
796
  \u53C2\u6570\uFF1A
797
797
  - questions: \u95EE\u9898\u6570\u7EC4\uFF081-4 \u4E2A\uFF09\uFF0C\u6BCF\u4E2A\u5305\u542B question \u6587\u672C\u548C options \u9009\u9879\u5217\u8868
798
- - \u7528\u6237\u53EF\u4EE5\u9009\u62E9\u9884\u8BBE\u9009\u9879\uFF0C\u4E5F\u53EF\u4EE5\u8F93\u5165\u81EA\u5B9A\u4E49\u56DE\u7B54`,parameters:{type:"object",properties:{questions:{type:"array",items:{type:"object",properties:{question:{type:"string",description:"\u95EE\u9898\u6587\u672C"},options:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"\u9009\u9879\u6807\u7B7E"},description:{type:"string",description:"\u9009\u9879\u8BF4\u660E"}},required:["label"]},description:"\u53EF\u9009\u9879\u5217\u8868\uFF082-4 \u4E2A\uFF09"},multiSelect:{type:"boolean",description:"\u662F\u5426\u5141\u8BB8\u591A\u9009"}},required:["question","options"]},description:"\u95EE\u9898\u5217\u8868\uFF081-4 \u4E2A\uFF09"}},required:["questions"]},async function(a,e){let t=a.questions||[];if(t.length===0)return "[ERROR] \u9700\u8981\u81F3\u5C11\u4E00\u4E2A\u95EE\u9898";let s=`ask_user_${++ub}_${Date.now()}`;return new Promise(n=>{lr.set(s,{resolve:n,questions:t}),cr=s,e?.signal&&e.signal.addEventListener("abort",()=>{lr.has(s)&&(n("[\u7528\u6237\u4E2D\u65AD]"),lr.delete(s),cr===s&&(cr=null));},{once:true}),setTimeout(()=>{lr.has(s)&&(n("[\u8D85\u65F6] \u7528\u6237\u672A\u5728 5 \u5206\u949F\u5185\u56DE\u7B54"),lr.delete(s),cr===s&&(cr=null));},300*1e3);})}};function db(a){let e=/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/,t=a.match(e);if(!t)return {metadata:{},body:a};let s=t[1],n=t[2],r={},i=s.split(`
799
- `),o="",c=null;for(let u of i){if(!u.trim()||u.trim().startsWith("#"))continue;let d=u.search(/\S/),p=u.trim();if(p.startsWith("- ")){let g=p.slice(2).trim();o&&Array.isArray(r[o])?r[o].push(g):c&&o&&(Array.isArray(c[o])||(c[o]=[]),c[o].push(g));continue}let h=p.indexOf(":");if(h>0){let g=p.slice(0,h).trim(),f=p.slice(h+1).trim();if(d===0)if(o=g,c=null,f==="")r[g]={},c=r[g];else if(f.startsWith("[")&&f.endsWith("]")){let b=f.slice(1,-1);r[g]=b.split(",").map(y=>y.trim().replace(/^["']|["']$/g,"")).filter(Boolean);}else r[g]=Kd(f);else if(c){if(f==="")c[g]={};else if(f.startsWith("[")&&f.endsWith("]")){let b=f.slice(1,-1);c[g]=b.split(",").map(y=>y.trim().replace(/^["']|["']$/g,"")).filter(Boolean);}else c[g]=Kd(f);o=g;}}}return {metadata:r,body:n}}function Kd(a){let e=a.replace(/^["']|["']$/g,"");if(e==="true")return true;if(e==="false")return false;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function pb(a){let e=a.name||"",t=a.description||"";if(!e)throw new Error("Skill metadata must have a name");if(!t)throw new Error("Skill metadata must have a description");if(e.length>64)throw new Error("Skill name must be at most 64 characters");if(t.length>200)throw new Error("Skill description must be at most 200 characters");let s={name:e,description:t};return a.dependencies&&(s.dependencies=a.dependencies),a.context&&(s.context=a.context),a.agent&&(s.agent=a.agent),a["user-invocable"]!==void 0&&(s["user-invocable"]=a["user-invocable"]),a.hooks&&typeof a.hooks=="object"&&(s.hooks=a.hooks),a.neox&&typeof a.neox=="object"&&(s.neox=a.neox),s}var ur=class{async loadFromDirectory(e,t){let s=[];if(!Me.existsSync(e))return s;let n=Me.readdirSync(e,{withFileTypes:true});for(let r of n){if(!r.isDirectory())continue;let i=te.join(e,r.name),o=te.join(i,"SKILL.md");if(Me.existsSync(o))try{let l=await this.loadSkill(i,r.name,t);s.push(l);}catch(l){console.warn(`Failed to load skill from ${i}:`,l instanceof Error?l.message:l);}}return s}async loadSkill(e,t,s){let n=te.join(e,"SKILL.md"),r=Me.readFileSync(n,"utf-8"),{metadata:i,body:o}=this.parseSkillFile(r),l=pb(i),c=await this.loadSupportFiles(e);return {id:t,path:n,source:s,metadata:l,content:o.trim(),supportFiles:c.size>0?c:void 0}}parseSkillFile(e){return db(e)}async loadSupportFiles(e){let t=new Map,s=Me.readdirSync(e,{withFileTypes:true});for(let n of s){if(!n.isFile()||n.name==="SKILL.md")continue;let r=te.join(e,n.name),i=te.extname(n.name).toLowerCase();if([".txt",".md",".json",".yaml",".yml",".sh",".js",".ts",".py"].includes(i))try{let l=Me.readFileSync(r,"utf-8");t.set(n.name,l);}catch{}}return t}};var ul=class{skills=new Map;aliasIndex=new Map;loader=new ur;initialized=false;watchers=[];debounceTimer=null;watchWorkDir;register(e){if(this.skills.set(e.id,e),e.metadata.neox?.aliases)for(let t of e.metadata.neox.aliases)this.aliasIndex.set(t,e.id);}unregister(e){let t=this.skills.get(e);if(t){if(t.metadata.neox?.aliases)for(let s of t.metadata.neox.aliases)this.aliasIndex.delete(s);this.skills.delete(e);}}find(e){let t=this.skills.get(e);if(t)return t;let s=this.aliasIndex.get(e);if(s)return this.skills.get(s);let n=e.toLowerCase();for(let[r,i]of Array.from(this.skills.entries()))if(r.toLowerCase()===n||i.metadata.name.toLowerCase()===n)return i}has(e){return this.find(e)!==void 0}list(e){let t=Array.from(this.skills.values());return e?.category&&(t=t.filter(s=>s.metadata.neox?.category===e.category)),e?.source&&(t=t.filter(s=>s.source===e.source)),e?.userInvocable!==void 0&&(t=t.filter(s=>s.metadata["user-invocable"]===e.userInvocable)),t.sort((s,n)=>s.id.localeCompare(n.id))}get size(){return this.skills.size}async loadBuiltin(){let e=fileURLToPath(import.meta.url),t=te.dirname(e),s=te.join(t,"..","skills","builtin"),n=await this.loader.loadFromDirectory(s,"builtin");for(let r of n)this.register(r);}async loadUser(){let e=te.join(In.homedir(),".neox","skills"),t=await this.loader.loadFromDirectory(e,"user");for(let s of t)this.register(s);}async loadWorkspace(e){let t=te.join(e,".neox","skills"),s=await this.loader.loadFromDirectory(t,"workspace");for(let n of s)this.register(n);}async initialize(e){this.initialized||(await this.loadBuiltin(),await this.loadUser(),e&&await this.loadWorkspace(e),this.initialized=true);}async refresh(e){this.skills.clear(),this.aliasIndex.clear(),this.initialized=false,await this.initialize(e);}watch(e){this.watchWorkDir=e;let t=[this.getUserSkillsDir(),...e?[this.getWorkspaceSkillsDir(e)]:[]];for(let s of t)if(Me.existsSync(s))try{let n=Me.watch(s,{recursive:!0},(r,i)=>{this.scheduleRefresh();});this.watchers.push(n);}catch{}}stopWatch(){for(let e of this.watchers)e.close();this.watchers=[],this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null);}scheduleRefresh(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{try{await this.refresh(this.watchWorkDir);}catch{}},500);}getSkillsForPrompt(){let e=this.list({userInvocable:true});if(e.length===0)return "";let t=["## Available Skills",""];for(let s of e){let n=s.metadata.neox?.aliases,r=n?.length?` (aliases: ${n.join(", ")})`:"";t.push(`- /${s.id}: ${s.metadata.description}${r}`);}return t.join(`
798
+ - \u7528\u6237\u53EF\u4EE5\u9009\u62E9\u9884\u8BBE\u9009\u9879\uFF0C\u4E5F\u53EF\u4EE5\u8F93\u5165\u81EA\u5B9A\u4E49\u56DE\u7B54`,parameters:{type:"object",properties:{questions:{type:"array",items:{type:"object",properties:{question:{type:"string",description:"\u95EE\u9898\u6587\u672C"},options:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"\u9009\u9879\u6807\u7B7E"},description:{type:"string",description:"\u9009\u9879\u8BF4\u660E"}},required:["label"]},description:"\u53EF\u9009\u9879\u5217\u8868\uFF082-4 \u4E2A\uFF09"},multiSelect:{type:"boolean",description:"\u662F\u5426\u5141\u8BB8\u591A\u9009"}},required:["question","options"]},description:"\u95EE\u9898\u5217\u8868\uFF081-4 \u4E2A\uFF09"}},required:["questions"]},async function(a,e){let t=a.questions||[];if(t.length===0)return "[ERROR] \u9700\u8981\u81F3\u5C11\u4E00\u4E2A\u95EE\u9898";let s=`ask_user_${++db}_${Date.now()}`;return new Promise(n=>{lr.set(s,{resolve:n,questions:t}),cr=s,e?.signal&&e.signal.addEventListener("abort",()=>{lr.has(s)&&(n("[\u7528\u6237\u4E2D\u65AD]"),lr.delete(s),cr===s&&(cr=null));},{once:true}),setTimeout(()=>{lr.has(s)&&(n("[\u8D85\u65F6] \u7528\u6237\u672A\u5728 5 \u5206\u949F\u5185\u56DE\u7B54"),lr.delete(s),cr===s&&(cr=null));},300*1e3);})}};function pb(a){let e=/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/,t=a.match(e);if(!t)return {metadata:{},body:a};let s=t[1],n=t[2],r={},i=s.split(`
799
+ `),o="",c=null;for(let u of i){if(!u.trim()||u.trim().startsWith("#"))continue;let d=u.search(/\S/),p=u.trim();if(p.startsWith("- ")){let g=p.slice(2).trim();o&&Array.isArray(r[o])?r[o].push(g):c&&o&&(Array.isArray(c[o])||(c[o]=[]),c[o].push(g));continue}let h=p.indexOf(":");if(h>0){let g=p.slice(0,h).trim(),f=p.slice(h+1).trim();if(d===0)if(o=g,c=null,f==="")r[g]={},c=r[g];else if(f.startsWith("[")&&f.endsWith("]")){let b=f.slice(1,-1);r[g]=b.split(",").map(y=>y.trim().replace(/^["']|["']$/g,"")).filter(Boolean);}else r[g]=Kd(f);else if(c){if(f==="")c[g]={};else if(f.startsWith("[")&&f.endsWith("]")){let b=f.slice(1,-1);c[g]=b.split(",").map(y=>y.trim().replace(/^["']|["']$/g,"")).filter(Boolean);}else c[g]=Kd(f);o=g;}}}return {metadata:r,body:n}}function Kd(a){let e=a.replace(/^["']|["']$/g,"");if(e==="true")return true;if(e==="false")return false;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function mb(a){let e=a.name||"",t=a.description||"";if(!e)throw new Error("Skill metadata must have a name");if(!t)throw new Error("Skill metadata must have a description");if(e.length>64)throw new Error("Skill name must be at most 64 characters");if(t.length>200)throw new Error("Skill description must be at most 200 characters");let s={name:e,description:t};return a.dependencies&&(s.dependencies=a.dependencies),a.context&&(s.context=a.context),a.agent&&(s.agent=a.agent),a["user-invocable"]!==void 0&&(s["user-invocable"]=a["user-invocable"]),a.hooks&&typeof a.hooks=="object"&&(s.hooks=a.hooks),a.neox&&typeof a.neox=="object"&&(s.neox=a.neox),s}var ur=class{async loadFromDirectory(e,t){let s=[];if(!Me.existsSync(e))return s;let n=Me.readdirSync(e,{withFileTypes:true});for(let r of n){if(!r.isDirectory())continue;let i=te.join(e,r.name),o=te.join(i,"SKILL.md");if(Me.existsSync(o))try{let l=await this.loadSkill(i,r.name,t);s.push(l);}catch(l){console.warn(`Failed to load skill from ${i}:`,l instanceof Error?l.message:l);}}return s}async loadSkill(e,t,s){let n=te.join(e,"SKILL.md"),r=Me.readFileSync(n,"utf-8"),{metadata:i,body:o}=this.parseSkillFile(r),l=mb(i),c=await this.loadSupportFiles(e);return {id:t,path:n,source:s,metadata:l,content:o.trim(),supportFiles:c.size>0?c:void 0}}parseSkillFile(e){return pb(e)}async loadSupportFiles(e){let t=new Map,s=Me.readdirSync(e,{withFileTypes:true});for(let n of s){if(!n.isFile()||n.name==="SKILL.md")continue;let r=te.join(e,n.name),i=te.extname(n.name).toLowerCase();if([".txt",".md",".json",".yaml",".yml",".sh",".js",".ts",".py"].includes(i))try{let l=Me.readFileSync(r,"utf-8");t.set(n.name,l);}catch{}}return t}};var ul=class{skills=new Map;aliasIndex=new Map;loader=new ur;initialized=false;watchers=[];debounceTimer=null;watchWorkDir;register(e){if(this.skills.set(e.id,e),e.metadata.neox?.aliases)for(let t of e.metadata.neox.aliases)this.aliasIndex.set(t,e.id);}unregister(e){let t=this.skills.get(e);if(t){if(t.metadata.neox?.aliases)for(let s of t.metadata.neox.aliases)this.aliasIndex.delete(s);this.skills.delete(e);}}find(e){let t=this.skills.get(e);if(t)return t;let s=this.aliasIndex.get(e);if(s)return this.skills.get(s);let n=e.toLowerCase();for(let[r,i]of Array.from(this.skills.entries()))if(r.toLowerCase()===n||i.metadata.name.toLowerCase()===n)return i}has(e){return this.find(e)!==void 0}list(e){let t=Array.from(this.skills.values());return e?.category&&(t=t.filter(s=>s.metadata.neox?.category===e.category)),e?.source&&(t=t.filter(s=>s.source===e.source)),e?.userInvocable!==void 0&&(t=t.filter(s=>s.metadata["user-invocable"]===e.userInvocable)),t.sort((s,n)=>s.id.localeCompare(n.id))}get size(){return this.skills.size}async loadBuiltin(){let e=fileURLToPath(import.meta.url),t=te.dirname(e),s=te.join(t,"..","skills","builtin"),n=await this.loader.loadFromDirectory(s,"builtin");for(let r of n)this.register(r);}async loadUser(){let e=te.join(In.homedir(),".neox","skills"),t=await this.loader.loadFromDirectory(e,"user");for(let s of t)this.register(s);}async loadWorkspace(e){let t=te.join(e,".neox","skills"),s=await this.loader.loadFromDirectory(t,"workspace");for(let n of s)this.register(n);}async initialize(e){this.initialized||(await this.loadBuiltin(),await this.loadUser(),e&&await this.loadWorkspace(e),this.initialized=true);}async refresh(e){this.skills.clear(),this.aliasIndex.clear(),this.initialized=false,await this.initialize(e);}watch(e){this.watchWorkDir=e;let t=[this.getUserSkillsDir(),...e?[this.getWorkspaceSkillsDir(e)]:[]];for(let s of t)if(Me.existsSync(s))try{let n=Me.watch(s,{recursive:!0},(r,i)=>{this.scheduleRefresh();});this.watchers.push(n);}catch{}}stopWatch(){for(let e of this.watchers)e.close();this.watchers=[],this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null);}scheduleRefresh(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{try{await this.refresh(this.watchWorkDir);}catch{}},500);}getSkillsForPrompt(){let e=this.list({userInvocable:true});if(e.length===0)return "";let t=["## Available Skills",""];for(let s of e){let n=s.metadata.neox?.aliases,r=n?.length?` (aliases: ${n.join(", ")})`:"";t.push(`- /${s.id}: ${s.metadata.description}${r}`);}return t.join(`
800
800
  `)}getUserSkillsDir(){return te.join(In.homedir(),".neox","skills")}getWorkspaceSkillsDir(e){return te.join(e,".neox","skills")}async importFromUrl(e,t,s){try{let n=new URL(e),r=await fetch(e);if(!r.ok)return {success:!1,error:`HTTP ${r.status}: ${r.statusText}`};let i=await r.text(),{metadata:o}=this.loader.parseSkillFile(i);if(!o.name)return {success:!1,error:"Invalid SKILL.md: missing name field"};let l=this.generateSkillId(o.name),c=t==="user"?this.getUserSkillsDir():this.getWorkspaceSkillsDir(s),u=te.join(c,l);Me.mkdirSync(u,{recursive:!0}),Me.writeFileSync(te.join(u,"SKILL.md"),i,"utf-8");let d=await this.loader.loadSkill(u,l,t);return this.register(d),{success:!0,skillId:l}}catch(n){return {success:false,error:n instanceof Error?n.message:String(n)}}}async importFromPath(e,t,s){try{let n=te.resolve(e),r=Me.statSync(n),i,o;if(r.isDirectory()?(i=te.join(n,"SKILL.md"),o=n):(i=n,o=te.dirname(n)),!Me.existsSync(i))return {success:!1,error:`SKILL.md not found at ${i}`};let l=Me.readFileSync(i,"utf-8"),{metadata:c}=this.loader.parseSkillFile(l);if(!c.name)return {success:!1,error:"Invalid SKILL.md: missing name field"};let u=this.generateSkillId(c.name),d=t==="user"?this.getUserSkillsDir():this.getWorkspaceSkillsDir(s),p=te.join(d,u);Me.mkdirSync(p,{recursive:!0}),Me.copyFileSync(i,te.join(p,"SKILL.md"));let h=Me.readdirSync(o,{withFileTypes:!0});for(let f of h)f.isFile()&&f.name!=="SKILL.md"&&Me.copyFileSync(te.join(o,f.name),te.join(p,f.name));let g=await this.loader.loadSkill(p,u,t);return this.register(g),{success:!0,skillId:u}}catch(n){return {success:false,error:n instanceof Error?n.message:String(n)}}}async createSkill(e){try{let{id:t,name:s,description:n,category:r,target:i,workDir:o}=e;if(!/^[a-z][a-z0-9-]*$/.test(t))return {success:!1,error:"Skill ID must start with lowercase letter and contain only lowercase letters, numbers, and hyphens"};if(this.has(t))return {success:!1,error:`Skill '${t}' already exists`};let l=i==="user"?this.getUserSkillsDir():this.getWorkspaceSkillsDir(o),c=te.join(l,t);if(Me.existsSync(c))return {success:!1,error:`Directory already exists: ${c}`};let u=`---
801
801
  name: "${s}"
802
802
  description: "${n}"
@@ -820,27 +820,27 @@ ${n}
820
820
  \u7528\u6237: /${t}
821
821
  AI: [\u6280\u80FD\u6267\u884C\u7ED3\u679C]
822
822
  \`\`\`
823
- `;Me.mkdirSync(c,{recursive:!0}),Me.writeFileSync(te.join(c,"SKILL.md"),u,"utf-8");let d=await this.loader.loadSkill(c,t,i);return this.register(d),{success:!0,path:c}}catch(t){return {success:false,error:t instanceof Error?t.message:String(t)}}}async deleteSkill(e){try{let t=this.find(e);if(!t)return {success:!1,error:`Skill '${e}' not found`};if(t.source==="builtin")return {success:!1,error:"Cannot delete built-in skills"};let s=te.dirname(t.path);return Me.rmSync(s,{recursive:!0,force:!0}),this.unregister(e),{success:!0}}catch(t){return {success:false,error:t instanceof Error?t.message:String(t)}}}generateSkillId(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32)}},ht=new ul;function gb(a){let e={named:{},positional:[],raw:a};if(!a.trim())return e;let t=[],s="",n=false,r="";for(let i of a)(i==='"'||i==="'")&&!n?(n=true,r=i):i===r&&n?(n=false,r=""):i===" "&&!n?(s.trim()&&t.push(s.trim()),s=""):s+=i;s.trim()&&t.push(s.trim());for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith("--")){let l=o.indexOf("=");if(l>0){let c=o.slice(2,l),u=o.slice(l+1);e.named[c]=u;}else {let c=o.slice(2),u=t[i+1];u&&!u.startsWith("-")?(e.named[c]=u,i++):e.named[c]="true";}}else if(o.startsWith("-")&&o.length===2){let l=o.slice(1),c=t[i+1];c&&!c.startsWith("-")?(e.named[l]=c,i++):e.named[l]="true";}else e.positional.push(o);}return e}var Ni=class{constructor(e){this.registry=e;}async execute(e,t,s){let n=this.registry.find(e);if(!n)return {success:false,error:`Skill not found: ${e}`};try{let r=gb(t);return {success:!0,output:this.buildPrompt(n,r,s)}}catch(r){return {success:false,error:r instanceof Error?r.message:String(r)}}}buildPrompt(e,t,s){let n=[];if(n.push(`# Skill: ${e.metadata.name}`),n.push(""),t.raw&&(n.push("## User Arguments"),n.push(`Raw: ${t.raw}`),Object.keys(t.named).length>0&&n.push(`Named: ${JSON.stringify(t.named)}`),t.positional.length>0&&n.push(`Positional: ${t.positional.join(", ")}`),n.push("")),n.push("## Context"),n.push(`Working Directory: ${s.workDir}`),n.push(""),n.push(e.content),e.supportFiles&&e.supportFiles.size>0){n.push(""),n.push("## Support Files");for(let[r,i]of Array.from(e.supportFiles.entries()))n.push(`### ${r}`),n.push("```"),n.push(i),n.push("```");}return n.join(`
824
- `)}getAllowedTools(e){return e.metadata.neox?.allowedTools}getRequiredTools(e){return e.metadata.neox?.requiredTools}getDangerLevel(e){return e.metadata.neox?.dangerLevel??"safe"}};var hb=new Set(["readfile","search","search_files","list_directory","show_tree","analyze_code","search_symbol","get_definitions","get_references","git_status","git_diff","git_blame","git_branch_list"]);function $i(a){if(a.parallelSafety==="safe"||a.parallelSafety==="unsafe")return a.parallelSafety;let e=a.permission?.category;return e==="read"?"safe":e==="write"||e==="execute"||e==="system"?"unsafe":hb.has(a.name)?"safe":"unsafe"}function Vd(a,e){let t={terminal:e?.terminal===true,editor:e?.editor===true,debug:e?.debug===true,trace:e?.trace===true},s=new Set,n=new Set;for(let r of a)s.add(r.name),$i(r)==="safe"&&n.add(r.name);return {capabilities:t,enabledTools:s,parallelSafeTools:n}}function Yd(a){return a.map(e=>({...e,parallelSafety:$i(e)}))}var op="NEOX_WORKDIR",wb="NEOX_WORKER",Cb=Wr(),Ke=Cb,we=Ke.logger;function kb(a){Ke=a,we=a.logger;}var cn=null;var dl=new Map,Sb=300*1e3;function xb(a,e){return e?a.filter(t=>!t.capabilities||t.capabilities.length===0?true:t.capabilities.every(s=>e[s]===true)):a}function Tb(){let a=process.env.NEOX_WORKER_ENTRY;if(a&&Me__default.existsSync(a))return a;try{let s=fileURLToPath(import.meta.url),n=te__default.resolve(te__default.dirname(s),".."),r=te__default.join(n,"cli","main.js");if(Me__default.existsSync(r))return r}catch{}let e=process.argv[1];if(e&&e.endsWith(".js")&&Me__default.existsSync(e)&&e.includes("cli")&&e.includes("main"))return e;let t=te__default.resolve(process.cwd(),"dist","cli","main.js");return Me__default.existsSync(t)?t:null}async function _b(a,e,t,s){if(process.env.NEOX_SHELL_WORKER_DISABLED==="1")return null;let n=Tb();return n?new Promise(r=>{let i=fork(n,[],{env:{...process.env,[wb]:"execute_shell"},stdio:["ignore","ignore","ignore","ipc"]}),o=false,l=Number(process.env.NEOX_SHELL_WORKER_WATCHDOG_MS)||6e4,c=setTimeout(()=>{we.warn("SHELL_WORKER",`execute_shell running > ${l}ms`,{command:a});},l),u=()=>{clearTimeout(c),s&&s.removeEventListener("abort",p),i.removeAllListeners();},d=h=>{o||(o=true,u(),r(h));},p=()=>{i.connected&&i.send({type:"abort"}),setTimeout(()=>{if(!o){try{i.kill("SIGTERM");}catch{}d({success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
823
+ `;Me.mkdirSync(c,{recursive:!0}),Me.writeFileSync(te.join(c,"SKILL.md"),u,"utf-8");let d=await this.loader.loadSkill(c,t,i);return this.register(d),{success:!0,path:c}}catch(t){return {success:false,error:t instanceof Error?t.message:String(t)}}}async deleteSkill(e){try{let t=this.find(e);if(!t)return {success:!1,error:`Skill '${e}' not found`};if(t.source==="builtin")return {success:!1,error:"Cannot delete built-in skills"};let s=te.dirname(t.path);return Me.rmSync(s,{recursive:!0,force:!0}),this.unregister(e),{success:!0}}catch(t){return {success:false,error:t instanceof Error?t.message:String(t)}}}generateSkillId(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32)}},ht=new ul;function hb(a){let e={named:{},positional:[],raw:a};if(!a.trim())return e;let t=[],s="",n=false,r="";for(let i of a)(i==='"'||i==="'")&&!n?(n=true,r=i):i===r&&n?(n=false,r=""):i===" "&&!n?(s.trim()&&t.push(s.trim()),s=""):s+=i;s.trim()&&t.push(s.trim());for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith("--")){let l=o.indexOf("=");if(l>0){let c=o.slice(2,l),u=o.slice(l+1);e.named[c]=u;}else {let c=o.slice(2),u=t[i+1];u&&!u.startsWith("-")?(e.named[c]=u,i++):e.named[c]="true";}}else if(o.startsWith("-")&&o.length===2){let l=o.slice(1),c=t[i+1];c&&!c.startsWith("-")?(e.named[l]=c,i++):e.named[l]="true";}else e.positional.push(o);}return e}var Ni=class{constructor(e){this.registry=e;}async execute(e,t,s){let n=this.registry.find(e);if(!n)return {success:false,error:`Skill not found: ${e}`};try{let r=hb(t);return {success:!0,output:this.buildPrompt(n,r,s)}}catch(r){return {success:false,error:r instanceof Error?r.message:String(r)}}}buildPrompt(e,t,s){let n=[];if(n.push(`# Skill: ${e.metadata.name}`),n.push(""),t.raw&&(n.push("## User Arguments"),n.push(`Raw: ${t.raw}`),Object.keys(t.named).length>0&&n.push(`Named: ${JSON.stringify(t.named)}`),t.positional.length>0&&n.push(`Positional: ${t.positional.join(", ")}`),n.push("")),n.push("## Context"),n.push(`Working Directory: ${s.workDir}`),n.push(""),n.push(e.content),e.supportFiles&&e.supportFiles.size>0){n.push(""),n.push("## Support Files");for(let[r,i]of Array.from(e.supportFiles.entries()))n.push(`### ${r}`),n.push("```"),n.push(i),n.push("```");}return n.join(`
824
+ `)}getAllowedTools(e){return e.metadata.neox?.allowedTools}getRequiredTools(e){return e.metadata.neox?.requiredTools}getDangerLevel(e){return e.metadata.neox?.dangerLevel??"safe"}};var fb=new Set(["readfile","search","search_files","list_directory","show_tree","analyze_code","search_symbol","get_definitions","get_references","git_status","git_diff","git_blame","git_branch_list"]);function $i(a){if(a.parallelSafety==="safe"||a.parallelSafety==="unsafe")return a.parallelSafety;let e=a.permission?.category;return e==="read"?"safe":e==="write"||e==="execute"||e==="system"?"unsafe":fb.has(a.name)?"safe":"unsafe"}function Vd(a,e){let t={terminal:e?.terminal===true,editor:e?.editor===true,debug:e?.debug===true,trace:e?.trace===true},s=new Set,n=new Set;for(let r of a)s.add(r.name),$i(r)==="safe"&&n.add(r.name);return {capabilities:t,enabledTools:s,parallelSafeTools:n}}function Yd(a){return a.map(e=>({...e,parallelSafety:$i(e)}))}var op="NEOX_WORKDIR",Cb="NEOX_WORKER",kb=Wr(),Ke=kb,we=Ke.logger;function Sb(a){Ke=a,we=a.logger;}var cn=null;var dl=new Map,xb=300*1e3;function Tb(a,e){return e?a.filter(t=>!t.capabilities||t.capabilities.length===0?true:t.capabilities.every(s=>e[s]===true)):a}function _b(){let a=process.env.NEOX_WORKER_ENTRY;if(a&&Me__default.existsSync(a))return a;try{let s=fileURLToPath(import.meta.url),n=te__default.resolve(te__default.dirname(s),".."),r=te__default.join(n,"cli","main.js");if(Me__default.existsSync(r))return r}catch{}let e=process.argv[1];if(e&&e.endsWith(".js")&&Me__default.existsSync(e)&&e.includes("cli")&&e.includes("main"))return e;let t=te__default.resolve(process.cwd(),"dist","cli","main.js");return Me__default.existsSync(t)?t:null}async function Rb(a,e,t,s){if(process.env.NEOX_SHELL_WORKER_DISABLED==="1")return null;let n=_b();return n?new Promise(r=>{let i=fork(n,[],{env:{...process.env,[Cb]:"execute_shell"},stdio:["ignore","ignore","ignore","ipc"]}),o=false,l=Number(process.env.NEOX_SHELL_WORKER_WATCHDOG_MS)||6e4,c=setTimeout(()=>{we.warn("SHELL_WORKER",`execute_shell running > ${l}ms`,{command:a});},l),u=()=>{clearTimeout(c),s&&s.removeEventListener("abort",p),i.removeAllListeners();},d=h=>{o||(o=true,u(),r(h));},p=()=>{i.connected&&i.send({type:"abort"}),setTimeout(()=>{if(!o){try{i.kill("SIGTERM");}catch{}d({success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
825
825
  \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${t}
826
826
  \u25B8 \u6267\u884C\u547D\u4EE4: ${a}
827
827
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
828
828
 
829
829
  \u26A0 \u547D\u4EE4\u88AB\u7528\u6237\u4E2D\u65AD
830
830
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,background:false});}},500),setTimeout(()=>{if(!o)try{i.kill("SIGKILL");}catch{}},2e3);};s&&(s.aborted?p():s.addEventListener("abort",p,{once:true})),i.on("message",h=>{if(!(!h||typeof h!="object")){if(h.type==="background_exit"){typeof h.pid=="number"&&(Ke.processManager.markCompleted(h.pid,h.exitCode??0),cn?.onUpdateByPid?.(h.pid,{status:(h.exitCode??0)===0?"done":"error",exitCode:h.exitCode??0}));return}h.type==="result"&&d({success:!!h.success,output:String(h.output??""),background:!!h.background,pid:typeof h.pid=="number"?h.pid:void 0,exitCode:typeof h.exitCode=="number"?h.exitCode:void 0});}}),i.on("exit",h=>{o||(we.warn("SHELL_WORKER","Worker exited before result",{code:h,command:a}),d(null));}),i.send({type:"execute_shell",payload:{command:a,background:e,workspaceRoot:t}});}):(we.warn("SHELL_WORKER","Worker entry not found, fallback to inline execution"),null)}function Qd(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(){let a=process.env[op];return a&&a.trim()?te__default.resolve(a):process.cwd()}function Ue(a){let e=st();if(!a||a.trim()===""||a.trim()===".")return e;let t=a.trim();if(t.startsWith("~/"))return te__default.resolve(te__default.join(In__default.homedir(),t.slice(2)));let s=te__default.isAbsolute(t),n=process.platform!=="win32"&&t.startsWith(`Users${te__default.sep}`);if(s||n){let l=!s&&n?te__default.join(te__default.sep,t):t;return te__default.resolve(l)}t=t.replace(/^[.\\/]+/,"");let r=t.split(/[\\/]+/).filter(Boolean),i=te__default.basename(e);r.length>0&&r[0]===i&&r.shift();let o=te__default.join(e,...r);return te__default.resolve(o)}function Le(a){let e=st(),t=te__default.relative(e,a);return t&&!t.startsWith("..")&&!te__default.isAbsolute(t)?t:a}var Zd=12e3,ep=4e3,tp=1e6;function Ht(a){let e=st(),t=te__default.relative(e,a);return t===""?true:!t.startsWith("..")&&!te__default.isAbsolute(t)}function Fi(a,e){return a.length<=e?{text:a,truncated:false}:{text:a.slice(0,e)+`
831
- ... (truncated)`,truncated:true}}async function We(a,e,t,s){let n=Date.now();return new Promise((r,i)=>{let o=spawn(a,e,{cwd:t,env:{...Ke.shellEnv.getShellEnv(),TERM:"dumb"},stdio:["ignore","pipe","pipe"],detached:false}),l="",c="",u=false;o.stdout?.on("data",h=>{l+=h.toString();}),o.stderr?.on("data",h=>{c+=h.toString();});let d=null;s?.timeoutMs&&(d=setTimeout(()=>{u=true,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL");},1e3);},s.timeoutMs));let p=()=>{u=true,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL");},1e3);};s?.signal&&(s.signal.aborted?p():s.signal.addEventListener("abort",p,{once:true})),o.on("close",h=>{d&&clearTimeout(d),s?.signal&&s.signal.removeEventListener("abort",p),r({stdout:l,stderr:c,exitCode:u?-1:h??0,durationMs:Date.now()-n});}),o.on("error",h=>{d&&clearTimeout(d),s?.signal&&s.signal.removeEventListener("abort",p),r({stdout:l,stderr:c,exitCode:-1,durationMs:Date.now()-n});});})}async function Ts(a,e){try{let t=await We("git",["rev-parse","--show-toplevel"],a,{signal:e,timeoutMs:8e3});return t.exitCode!==0||!t.stdout.trim()?{error:"Not a git repository"}:{repoRoot:t.stdout.trim()}}catch(t){return {error:t?.message||"Not a git repository"}}}function Eb(a){let e=a.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var Ib={name:"write_file",description:"Write content to a file (create or overwrite)",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to write"},content:{type:"string",description:"Content to write to the file"},mode:{type:"string",description:"Write mode: overwrite or append",enum:["overwrite","append"]}},required:["file_path","content"]},async function({file_path:a,content:e,mode:t="overwrite"}){if(!a)return JSON.stringify(X("write_file","error","Missing required parameter: file_path",{error:"file_path is required",verify_hint:"Please provide the file_path parameter."}));if(e==null)return JSON.stringify(X("write_file","error","Missing required parameter: content",{error:"content is required",verify_hint:"Please provide the content parameter with the text to write."}));let s=typeof e=="string"?e:String(e);if(s.trim()==="")return JSON.stringify(X("write_file","error","Content is empty - this is likely an error",{error:"Empty content provided",verify_hint:"Please provide non-empty content to write."}));let n=Ue(a),r=createHash("sha256").update(s).digest("hex").substring(0,16),i=dl.get(n),o=Date.now();if(i&&i.checksum===r&&i.success&&o-i.timestamp<Sb){let l=s.split(`
831
+ ... (truncated)`,truncated:true}}async function We(a,e,t,s){let n=Date.now();return new Promise((r,i)=>{let o=spawn(a,e,{cwd:t,env:{...Ke.shellEnv.getShellEnv(),TERM:"dumb"},stdio:["ignore","pipe","pipe"],detached:false}),l="",c="",u=false;o.stdout?.on("data",h=>{l+=h.toString();}),o.stderr?.on("data",h=>{c+=h.toString();});let d=null;s?.timeoutMs&&(d=setTimeout(()=>{u=true,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL");},1e3);},s.timeoutMs));let p=()=>{u=true,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL");},1e3);};s?.signal&&(s.signal.aborted?p():s.signal.addEventListener("abort",p,{once:true})),o.on("close",h=>{d&&clearTimeout(d),s?.signal&&s.signal.removeEventListener("abort",p),r({stdout:l,stderr:c,exitCode:u?-1:h??0,durationMs:Date.now()-n});}),o.on("error",h=>{d&&clearTimeout(d),s?.signal&&s.signal.removeEventListener("abort",p),r({stdout:l,stderr:c,exitCode:-1,durationMs:Date.now()-n});});})}async function Ts(a,e){try{let t=await We("git",["rev-parse","--show-toplevel"],a,{signal:e,timeoutMs:8e3});return t.exitCode!==0||!t.stdout.trim()?{error:"Not a git repository"}:{repoRoot:t.stdout.trim()}}catch(t){return {error:t?.message||"Not a git repository"}}}function Ib(a){let e=a.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var Mb={name:"write_file",description:"Write content to a file (create or overwrite)",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to write"},content:{type:"string",description:"Content to write to the file"},mode:{type:"string",description:"Write mode: overwrite or append",enum:["overwrite","append"]}},required:["file_path","content"]},async function({file_path:a,content:e,mode:t="overwrite"}){if(!a)return JSON.stringify(X("write_file","error","Missing required parameter: file_path",{error:"file_path is required",verify_hint:"Please provide the file_path parameter."}));if(e==null)return JSON.stringify(X("write_file","error","Missing required parameter: content",{error:"content is required",verify_hint:"Please provide the content parameter with the text to write."}));let s=typeof e=="string"?e:String(e);if(s.trim()==="")return JSON.stringify(X("write_file","error","Content is empty - this is likely an error",{error:"Empty content provided",verify_hint:"Please provide non-empty content to write."}));let n=Ue(a),r=createHash("sha256").update(s).digest("hex").substring(0,16),i=dl.get(n),o=Date.now();if(i&&i.checksum===r&&i.success&&o-i.timestamp<xb){let l=s.split(`
832
832
  `).length;return JSON.stringify(X("write_file","already_done",`File already written with identical content (${l} lines, ${s.length} bytes)`,{file_path:n,checksum:r,verify_hint:`Use "readfile ${a}" to verify the content if needed.`,metadata:{lines:l,bytes:s.length}}))}try{let l=!1;try{await ce__default.access(n),l=!0;}catch{}await ce__default.mkdir(te__default.dirname(n),{recursive:!0}),t==="append"?await ce__default.appendFile(n,s,"utf-8"):await ce__default.writeFile(n,s,"utf-8"),dl.set(n,{checksum:r,timestamp:o,success:!0});let c=s.split(`
833
- `).length,u=l?"updated":"created";return JSON.stringify(X("write_file","success",`File ${u}: ${te__default.basename(n)} (${c} lines, ${s.length} bytes)`,{file_path:n,checksum:r,verify_hint:`Use "readfile ${a}" to verify the content.`,metadata:{action:u,lines:c,bytes:s.length}}))}catch(l){return dl.set(n,{checksum:r,timestamp:o,success:false}),JSON.stringify(X("write_file","error",`Failed to write file: ${l.message}`,{file_path:n,error:l.message,verify_hint:"Check file permissions and path validity."}))}}};function Mb(a){let e=a.includes(`\r
833
+ `).length,u=l?"updated":"created";return JSON.stringify(X("write_file","success",`File ${u}: ${te__default.basename(n)} (${c} lines, ${s.length} bytes)`,{file_path:n,checksum:r,verify_hint:`Use "readfile ${a}" to verify the content.`,metadata:{action:u,lines:c,bytes:s.length}}))}catch(l){return dl.set(n,{checksum:r,timestamp:o,success:false}),JSON.stringify(X("write_file","error",`Failed to write file: ${l.message}`,{file_path:n,error:l.message,verify_hint:"Check file permissions and path validity."}))}}};function Pb(a){let e=a.includes(`\r
834
834
  `)?`\r
835
835
  `:`
836
- `,t=a.endsWith(e),s=a.split(/\r?\n/);return t&&s[s.length-1]===""&&s.pop(),{lines:s,lineEnding:e,hasTrailingNewline:t}}function sp(a){let e=a.trim(),t="";for(let s of e)switch(s){case "\u2010":case "\u2011":case "\u2012":case "\u2013":case "\u2014":case "\u2015":case "\u2212":t+="-";break;case "\u2018":case "\u2019":case "\u201A":case "\u201B":t+="'";break;case "\u201C":case "\u201D":case "\u201E":case "\u201F":t+='"';break;case "\xA0":case "\u2002":case "\u2003":case "\u2004":case "\u2005":case "\u2006":case "\u2007":case "\u2008":case "\u2009":case "\u200A":case "\u202F":case "\u205F":case "\u3000":t+=" ";break;default:t+=s;break}return t}function pl(a,e,t){if(e.length===0)return t;if(e.length>a.length)return null;let s=a.length-e.length;for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i]!==e[i]){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i].trimEnd()!==e[i].trimEnd()){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i].trim()!==e[i].trim()){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(sp(a[n+i])!==sp(e[i])){r=false;break}if(r)return n}return null}var Pb=2e5;function Db(a,e){let t=a.length,s=e.length;if(t*s>Pb)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 Lb(a,e){if(a.length===0&&e.length===0)return [];let t=Db(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 Ob={name:"edit_file",description:`Edit file by replacing a target block with a new block.
836
+ `,t=a.endsWith(e),s=a.split(/\r?\n/);return t&&s[s.length-1]===""&&s.pop(),{lines:s,lineEnding:e,hasTrailingNewline:t}}function sp(a){let e=a.trim(),t="";for(let s of e)switch(s){case "\u2010":case "\u2011":case "\u2012":case "\u2013":case "\u2014":case "\u2015":case "\u2212":t+="-";break;case "\u2018":case "\u2019":case "\u201A":case "\u201B":t+="'";break;case "\u201C":case "\u201D":case "\u201E":case "\u201F":t+='"';break;case "\xA0":case "\u2002":case "\u2003":case "\u2004":case "\u2005":case "\u2006":case "\u2007":case "\u2008":case "\u2009":case "\u200A":case "\u202F":case "\u205F":case "\u3000":t+=" ";break;default:t+=s;break}return t}function pl(a,e,t){if(e.length===0)return t;if(e.length>a.length)return null;let s=a.length-e.length;for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i]!==e[i]){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i].trimEnd()!==e[i].trimEnd()){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i].trim()!==e[i].trim()){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(sp(a[n+i])!==sp(e[i])){r=false;break}if(r)return n}return null}var Db=2e5;function Lb(a,e){let t=a.length,s=e.length;if(t*s>Db)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 Ob(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 Nb={name:"edit_file",description:`Edit file by replacing a target block with a new block.
837
837
  Edits apply line-level hunks (only changed lines are replaced).
838
838
  Matches are robust (exact -> trim_end -> trim -> normalize) to avoid brittle edits.
839
- Use change_context to anchor a location and keep old_string minimal.`,parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to edit"},path:{type:"string",description:"Alias of file_path (fallback)"},filePath:{type:"string",description:"Alias of file_path (camelCase fallback)"},file:{type:"string",description:"Alias of file_path (short fallback)"},old_string:{type:"string",description:"Exact string to find and replace (must match exactly, including whitespace)"},old:{type:"string",description:"Alias of old_string (fallback)"},new_string:{type:"string",description:"New string to replace with"},new:{type:"string",description:"Alias of new_string (fallback)"},change_context:{type:"string",description:"Optional anchor (line or block) to locate the edit area (apply_patch-style @@ context)"},changeContext:{type:"string",description:"Alias of change_context (camelCase fallback)"},context:{type:"string",description:"Alias of change_context (fallback)"},replace_all:{type:"boolean",description:"Replace all occurrences (default: false, only first match)"},replaceAll:{type:"boolean",description:"Alias of replace_all (camelCase fallback)"}},required:["file_path","old_string","new_string"]},async function(a){let e=a.file_path||a.path||a.filePath||a.file,t=a.old_string??a.old,s=a.new_string??a.new,n=a.replace_all??a.replaceAll??false,r=a.change_context??a.changeContext??a.context,i=Ue(e);Le(i);if(!e)return JSON.stringify(X("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(X("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(s==null)return JSON.stringify(X("edit_file","error","Missing required parameter: new_string",{error:"new_string is required"}));let l;try{l=await ce__default.readFile(i,"utf-8");}catch{return JSON.stringify(X("edit_file","error",`File not found: ${e}`,{file_path:i,error:"File not found",verify_hint:"Use write_file to create a new file, or check the file path."}))}try{let{lines:c,lineEnding:u,hasTrailingNewline:d}=Mb(l),p=t.split(/\r?\n/),h=s.split(/\r?\n/);if(p.length===1&&p[0]==="")return JSON.stringify(X("edit_file","error","old_string cannot be empty",{file_path:i,error:"old_string cannot be empty"}));let g=0;if(r){let v=r.split(/\r?\n/),E=pl(c,v,0);if(E===null)return JSON.stringify(X("edit_file","error",`change_context not found in ${te__default.basename(i)}`,{file_path:i,error:"change_context not found",verify_hint:`Use "readfile ${e}" to verify the context lines.`}));g=E+v.length;}let f=[],b=g;for(;b<=c.length;){let v=pl(c,p,b),E=p,L=h;if(v===null&&p.length>0&&p[p.length-1]===""){let I=p.slice(0,-1);I.length>0&&(v=pl(c,I,b),v!==null&&(E=I,L=h[h.length-1]===""?h.slice(0,-1):h));}if(v===null)break;f.push({start:v,oldLines:E,newLines:L}),b=v+E.length;}if(f.length===0)return JSON.stringify(X("edit_file","error",`Target block not found in ${te__default.basename(i)}`,{file_path:i,error:"old_string not found",verify_hint:`Use "readfile ${e}" and reduce old_string or provide change_context.`}));let y=n?f:[f[0]],w=c.slice(),C=[];for(let v of y.slice().reverse()){let E=c.slice(v.start,v.start+v.oldLines.length),L=Lb(E,v.newLines);if(L.length!==0){for(let I of L)C.push({startLine:v.start+I.oldStart+1,oldLines:I.oldLines,newLines:I.newLines});for(let I of L.slice().reverse())w.splice(v.start+I.oldStart,I.oldLines.length,...I.newLines);}}d&&(w=[...w,""]);let k=w.join(u);if(k===l)return JSON.stringify(X("edit_file","already_done","No changes needed (content already matches)",{file_path:i,verify_hint:`Use "readfile ${e}" to verify the content if needed.`}));await ce__default.writeFile(i,k,"utf-8");let T=C.slice().sort((v,E)=>v.startLine-E.startLine),_=T[0],M=_?_.oldLines:[],F=_?_.newLines:[],x=_?_.startLine:1,R=w.length,j=!n&&f.length>1?`Found ${f.length} matches, only replaced the first one. Use replace_all=true to replace all.`:void 0;return JSON.stringify(X("edit_file","success",`Edited ${te__default.basename(i)}: ${y.length} replacement(s) at line ${x}`,{file_path:i,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:y.length,start_line:x,old_lines:M.length,new_lines:F.length,total_lines:R,warning:j,hunks:T.map(v=>({old_string:v.oldLines.join(`
839
+ Use change_context to anchor a location and keep old_string minimal.`,parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to edit"},path:{type:"string",description:"Alias of file_path (fallback)"},filePath:{type:"string",description:"Alias of file_path (camelCase fallback)"},file:{type:"string",description:"Alias of file_path (short fallback)"},old_string:{type:"string",description:"Exact string to find and replace (must match exactly, including whitespace)"},old:{type:"string",description:"Alias of old_string (fallback)"},new_string:{type:"string",description:"New string to replace with"},new:{type:"string",description:"Alias of new_string (fallback)"},change_context:{type:"string",description:"Optional anchor (line or block) to locate the edit area (apply_patch-style @@ context)"},changeContext:{type:"string",description:"Alias of change_context (camelCase fallback)"},context:{type:"string",description:"Alias of change_context (fallback)"},replace_all:{type:"boolean",description:"Replace all occurrences (default: false, only first match)"},replaceAll:{type:"boolean",description:"Alias of replace_all (camelCase fallback)"}},required:["file_path","old_string","new_string"]},async function(a){let e=a.file_path||a.path||a.filePath||a.file,t=a.old_string??a.old,s=a.new_string??a.new,n=a.replace_all??a.replaceAll??false,r=a.change_context??a.changeContext??a.context,i=Ue(e);Le(i);if(!e)return JSON.stringify(X("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(X("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(s==null)return JSON.stringify(X("edit_file","error","Missing required parameter: new_string",{error:"new_string is required"}));let l;try{l=await ce__default.readFile(i,"utf-8");}catch{return JSON.stringify(X("edit_file","error",`File not found: ${e}`,{file_path:i,error:"File not found",verify_hint:"Use write_file to create a new file, or check the file path."}))}try{let{lines:c,lineEnding:u,hasTrailingNewline:d}=Pb(l),p=t.split(/\r?\n/),h=s.split(/\r?\n/);if(p.length===1&&p[0]==="")return JSON.stringify(X("edit_file","error","old_string cannot be empty",{file_path:i,error:"old_string cannot be empty"}));let g=0;if(r){let v=r.split(/\r?\n/),E=pl(c,v,0);if(E===null)return JSON.stringify(X("edit_file","error",`change_context not found in ${te__default.basename(i)}`,{file_path:i,error:"change_context not found",verify_hint:`Use "readfile ${e}" to verify the context lines.`}));g=E+v.length;}let f=[],b=g;for(;b<=c.length;){let v=pl(c,p,b),E=p,L=h;if(v===null&&p.length>0&&p[p.length-1]===""){let I=p.slice(0,-1);I.length>0&&(v=pl(c,I,b),v!==null&&(E=I,L=h[h.length-1]===""?h.slice(0,-1):h));}if(v===null)break;f.push({start:v,oldLines:E,newLines:L}),b=v+E.length;}if(f.length===0)return JSON.stringify(X("edit_file","error",`Target block not found in ${te__default.basename(i)}`,{file_path:i,error:"old_string not found",verify_hint:`Use "readfile ${e}" and reduce old_string or provide change_context.`}));let y=n?f:[f[0]],w=c.slice(),C=[];for(let v of y.slice().reverse()){let E=c.slice(v.start,v.start+v.oldLines.length),L=Ob(E,v.newLines);if(L.length!==0){for(let I of L)C.push({startLine:v.start+I.oldStart+1,oldLines:I.oldLines,newLines:I.newLines});for(let I of L.slice().reverse())w.splice(v.start+I.oldStart,I.oldLines.length,...I.newLines);}}d&&(w=[...w,""]);let k=w.join(u);if(k===l)return JSON.stringify(X("edit_file","already_done","No changes needed (content already matches)",{file_path:i,verify_hint:`Use "readfile ${e}" to verify the content if needed.`}));await ce__default.writeFile(i,k,"utf-8");let T=C.slice().sort((v,E)=>v.startLine-E.startLine),_=T[0],M=_?_.oldLines:[],F=_?_.newLines:[],x=_?_.startLine:1,R=w.length,j=!n&&f.length>1?`Found ${f.length} matches, only replaced the first one. Use replace_all=true to replace all.`:void 0;return JSON.stringify(X("edit_file","success",`Edited ${te__default.basename(i)}: ${y.length} replacement(s) at line ${x}`,{file_path:i,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:y.length,start_line:x,old_lines:M.length,new_lines:F.length,total_lines:R,warning:j,hunks:T.map(v=>({old_string:v.oldLines.join(`
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(`
843
- `),start_line:x,old_line_count:M.length,new_line_count:F.length}}}))}catch(c){return JSON.stringify(X("edit_file","error",`Failed to edit file: ${c.message}`,{file_path:i,error:c.message,verify_hint:"Check file permissions or try using write_file to rewrite the entire file."}))}}},Nb={name:"search_files",description:`Fast file pattern matching tool (Glob).
843
+ `),start_line:x,old_line_count:M.length,new_line_count:F.length}}}))}catch(c){return JSON.stringify(X("edit_file","error",`Failed to edit file: ${c.message}`,{file_path:i,error:c.message,verify_hint:"Check file permissions or try using write_file to rewrite the entire file."}))}}},$b={name:"search_files",description:`Fast file pattern matching tool (Glob).
844
844
 
845
845
  Use this to find files by name patterns:
846
846
  - "**/*.ts" - all TypeScript files
@@ -855,13 +855,13 @@ For searching file CONTENTS, use search instead.`,parameters:{type:"object",prop
855
855
  - \u5C1D\u8BD5\u66F4\u5BBD\u6CDB\u7684\u6A21\u5F0F: "**/*${a.replace(/\*\*/g,"").replace(/\*/g,"")}"`;n.sort();let r=[`\u2713 \u627E\u5230 ${n.length} \u4E2A\u6587\u4EF6`];r.push(`\u25B8 \u76EE\u5F55: ${Le(s)}`),r.push(`\u25B8 \u6A21\u5F0F: ${a}
856
856
  `);let i=50;return n.slice(0,i).forEach(l=>{r.push(` ${l}`);}),n.length>i&&r.push(`
857
857
  ... \u8FD8\u6709 ${n.length-i} \u4E2A\u6587\u4EF6`),r.join(`
858
- `)}catch(s){return `\u2717 \u641C\u7D22\u5931\u8D25: ${s.message}`}}},$b={name:"list_directory",description:"List contents of a directory",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path (default: current directory)"},show_hidden:{type:"boolean",description:"Show hidden files"}}},async function({directory:a=".",show_hidden:e=false}){try{let t=Ue(a),s=await ce__default.readdir(t,{withFileTypes:!0}),n=e?s:s.filter(l=>!l.name.startsWith(".")),r=n.filter(l=>l.isDirectory()).map(l=>l.name),i=n.filter(l=>l.isFile()).map(l=>l.name),o=[`\u2713 \u76EE\u5F55: ${Le(t)}
858
+ `)}catch(s){return `\u2717 \u641C\u7D22\u5931\u8D25: ${s.message}`}}},Fb={name:"list_directory",description:"List contents of a directory",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path (default: current directory)"},show_hidden:{type:"boolean",description:"Show hidden files"}}},async function({directory:a=".",show_hidden:e=false}){try{let t=Ue(a),s=await ce__default.readdir(t,{withFileTypes:!0}),n=e?s:s.filter(l=>!l.name.startsWith(".")),r=n.filter(l=>l.isDirectory()).map(l=>l.name),i=n.filter(l=>l.isFile()).map(l=>l.name),o=[`\u2713 \u76EE\u5F55: ${Le(t)}
859
859
  `];if(r.length>0&&(o.push("\u5B50\u76EE\u5F55:"),r.forEach(l=>o.push(` - ${l}/`))),i.length>0){o.push(`
860
860
  \u6587\u4EF6:`);for(let l of i){let c=await ce__default.stat(te__default.join(t,l)),u=c.size<1024?`${c.size}B`:c.size<1024*1024?`${(c.size/1024).toFixed(1)}KB`:`${(c.size/(1024*1024)).toFixed(1)}MB`;o.push(` - ${l} (${u})`);}}return r.length===0&&i.length===0&&o.push("(\u7A7A\u76EE\u5F55)"),o.join(`
861
- `)}catch(t){return `\u2717 \u5217\u51FA\u76EE\u5F55\u5931\u8D25: ${t.message}`}}},Fb={name:"create_directory",description:"Create a new directory",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path to create"}},required:["directory"]},async function({directory:a}){if(!a)return JSON.stringify(X("create_directory","error","Missing required parameter: directory",{error:"directory path is required",verify_hint:"Please provide the directory path to create."}));let e=Ue(a),t=Le(e);try{try{if((await ce__default.stat(e)).isDirectory())return JSON.stringify(X("create_directory","already_done",`Directory already exists: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${a}" to view contents.`}))}catch{}return await ce__default.mkdir(e,{recursive:!0}),JSON.stringify(X("create_directory","success",`Directory created: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${a}" to verify.`}))}catch(s){return JSON.stringify(X("create_directory","error",`Failed to create directory: ${s.message}`,{file_path:e,error:s.message,verify_hint:"Check path validity and permissions."}))}}},jb={name:"delete_file",description:"Delete a file or directory (directory requires recursive=true)",parameters:{type:"object",properties:{path:{type:"string",description:"Path to the file or directory to delete"},recursive:{type:"boolean",description:"Allow deleting directories recursively (default: false)"},force:{type:"boolean",description:"Ignore missing paths (default: false)"}},required:["path"]},permission:{category:"write",allowInAskMode:false},async function({path:a,recursive:e=false,force:t=false}){if(!a)return JSON.stringify(X("delete_file","error","Missing required parameter: path",{error:"path is required"}));let s=Ue(a),n=Le(s),r=st();if(!Ht(s))return JSON.stringify(X("delete_file","error","Path is \u062E\u0627\u0631\u062C workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:s,error:"Path is outside workspace",verify_hint:"Use a path within the workspace."}));if(s===r)return JSON.stringify(X("delete_file","error","Refusing to delete workspace root",{file_path:s,error:"Refusing to delete workspace root"}));try{let i=await ce__default.lstat(s).catch(()=>null);if(!i)return JSON.stringify(t?X("delete_file","already_done",`Path already removed: ${n}`,{file_path:s}):X("delete_file","error",`Path not found: ${n}`,{file_path:s,error:"Path not found"}));if(i.isDirectory()){if(!e)return JSON.stringify(X("delete_file","error",`Refusing to delete directory without recursive=true: ${n}`,{file_path:s,error:"Directory deletion requires recursive=true"}));await ce__default.rm(s,{recursive:!0,force:t});}else await ce__default.rm(s,{force:t});return JSON.stringify(X("delete_file","success",`Deleted: ${n}`,{file_path:s,verify_hint:`Use "list_directory ${te__default.dirname(n)}" to verify.`}))}catch(i){return JSON.stringify(X("delete_file","error",`Failed to delete: ${n}`,{file_path:s,error:i.message}))}}},Bb={name:"rename_file",description:"Rename or move a file/directory within the workspace",parameters:{type:"object",properties:{source_path:{type:"string",description:"Existing path to rename or move"},destination_path:{type:"string",description:"New path"},overwrite:{type:"boolean",description:"Overwrite destination if it exists (default: false)"},create_dirs:{type:"boolean",description:"Create destination parent directories if missing (default: true)"}},required:["source_path","destination_path"]},permission:{category:"write",allowInAskMode:false},async function({source_path:a,destination_path:e,overwrite:t=false,create_dirs:s=true}){if(!a||!e)return JSON.stringify(X("rename_file","error","Missing required parameters: source_path, destination_path",{error:"source_path and destination_path are required"}));let n=Ue(a),r=Ue(e),i=Le(n),o=Le(r),l=st();if(!Ht(n)||!Ht(r))return JSON.stringify(X("rename_file","error","Path is outside workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:`${n} -> ${r}`,error:"Path is outside workspace"}));if(n===l||r===l)return JSON.stringify(X("rename_file","error","Refusing to rename workspace root",{file_path:n}));try{await ce__default.lstat(n);}catch{return JSON.stringify(X("rename_file","error",`Source not found: ${i}`,{file_path:n,error:"Source not found"}))}let c=await ce__default.lstat(r).catch(()=>null);if(c&&!t)return JSON.stringify(X("rename_file","error",`Destination already exists: ${o}`,{file_path:r,error:"Destination already exists"}));try{return c&&t&&await ce__default.rm(r,{recursive:!0,force:!0}),s&&await ce__default.mkdir(te__default.dirname(r),{recursive:!0}),await ce__default.rename(n,r),JSON.stringify(X("rename_file","success",`Renamed: ${i} \u2192 ${o}`,{file_path:r,verify_hint:`Use "list_directory ${te__default.dirname(o)}" to verify.`,metadata:{from:n,to:r}}))}catch(u){return JSON.stringify(X("rename_file","error",`Failed to rename: ${i}`,{file_path:n,error:u.message}))}}},Gb={name:"apply_patch",description:"Apply a unified diff patch (git apply style)",parameters:{type:"object",properties:{patch:{type:"string",description:"Unified diff patch content"},strip:{type:"number",description:"Strip leading path components (git apply -p, default: 0)"},reverse:{type:"boolean",description:"Apply patch in reverse (default: false)"}},required:["patch"]},permission:{category:"write",allowInAskMode:false},async function({patch:a,strip:e=0,reverse:t=false}){if(!a||typeof a!="string")return JSON.stringify(X("apply_patch","error","Missing required parameter: patch",{error:"patch is required"}));if(!Number.isInteger(e)||e<0||e>10)return JSON.stringify(X("apply_patch","error","Invalid strip value (must be an integer between 0 and 10)",{error:"Invalid strip value"}));if(Buffer.byteLength(a,"utf8")>tp)return JSON.stringify(X("apply_patch","error",`Patch too large (max ${tp} bytes)`,{error:"Patch too large"}));let s=a.split(`
862
- `).filter(c=>c.startsWith("+++ ")||c.startsWith("--- "));for(let c of s){let u=c.slice(4).trim();if(u==="/dev/null")continue;let d=u.replace(/^a\//,"").replace(/^b\//,"");if(d.startsWith("/")||/^[A-Za-z]:[\\/]/.test(d))return JSON.stringify(X("apply_patch","error","Patch contains absolute paths",{error:"Absolute paths are not allowed in patch"}));if(d.split(/[\\/]+/).includes(".."))return JSON.stringify(X("apply_patch","error","Patch contains path traversal",{error:"Path traversal is not allowed in patch"}))}let n=st(),{repoRoot:r,error:i}=await Ts(n);if(!r)return JSON.stringify(X("apply_patch","error",`Not a git repository: ${i||"unknown error"}`,{error:"Not a git repository"}));let o=await ce__default.mkdtemp(te__default.join(In__default.tmpdir(),"neox-patch-")),l=te__default.join(o,"apply.patch");try{await ce__default.writeFile(l,a,"utf8");let c=["apply"];e>0&&c.push(`-p${e}`),t&&c.push("--reverse");let u=await We("git",[...c,"--check",l],r);if(u.exitCode!==0){let p=[u.stdout,u.stderr].filter(Boolean).join(`
861
+ `)}catch(t){return `\u2717 \u5217\u51FA\u76EE\u5F55\u5931\u8D25: ${t.message}`}}},jb={name:"create_directory",description:"Create a new directory",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path to create"}},required:["directory"]},async function({directory:a}){if(!a)return JSON.stringify(X("create_directory","error","Missing required parameter: directory",{error:"directory path is required",verify_hint:"Please provide the directory path to create."}));let e=Ue(a),t=Le(e);try{try{if((await ce__default.stat(e)).isDirectory())return JSON.stringify(X("create_directory","already_done",`Directory already exists: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${a}" to view contents.`}))}catch{}return await ce__default.mkdir(e,{recursive:!0}),JSON.stringify(X("create_directory","success",`Directory created: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${a}" to verify.`}))}catch(s){return JSON.stringify(X("create_directory","error",`Failed to create directory: ${s.message}`,{file_path:e,error:s.message,verify_hint:"Check path validity and permissions."}))}}},Bb={name:"delete_file",description:"Delete a file or directory (directory requires recursive=true)",parameters:{type:"object",properties:{path:{type:"string",description:"Path to the file or directory to delete"},recursive:{type:"boolean",description:"Allow deleting directories recursively (default: false)"},force:{type:"boolean",description:"Ignore missing paths (default: false)"}},required:["path"]},permission:{category:"write",allowInAskMode:false},async function({path:a,recursive:e=false,force:t=false}){if(!a)return JSON.stringify(X("delete_file","error","Missing required parameter: path",{error:"path is required"}));let s=Ue(a),n=Le(s),r=st();if(!Ht(s))return JSON.stringify(X("delete_file","error","Path is \u062E\u0627\u0631\u062C workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:s,error:"Path is outside workspace",verify_hint:"Use a path within the workspace."}));if(s===r)return JSON.stringify(X("delete_file","error","Refusing to delete workspace root",{file_path:s,error:"Refusing to delete workspace root"}));try{let i=await ce__default.lstat(s).catch(()=>null);if(!i)return JSON.stringify(t?X("delete_file","already_done",`Path already removed: ${n}`,{file_path:s}):X("delete_file","error",`Path not found: ${n}`,{file_path:s,error:"Path not found"}));if(i.isDirectory()){if(!e)return JSON.stringify(X("delete_file","error",`Refusing to delete directory without recursive=true: ${n}`,{file_path:s,error:"Directory deletion requires recursive=true"}));await ce__default.rm(s,{recursive:!0,force:t});}else await ce__default.rm(s,{force:t});return JSON.stringify(X("delete_file","success",`Deleted: ${n}`,{file_path:s,verify_hint:`Use "list_directory ${te__default.dirname(n)}" to verify.`}))}catch(i){return JSON.stringify(X("delete_file","error",`Failed to delete: ${n}`,{file_path:s,error:i.message}))}}},Gb={name:"rename_file",description:"Rename or move a file/directory within the workspace",parameters:{type:"object",properties:{source_path:{type:"string",description:"Existing path to rename or move"},destination_path:{type:"string",description:"New path"},overwrite:{type:"boolean",description:"Overwrite destination if it exists (default: false)"},create_dirs:{type:"boolean",description:"Create destination parent directories if missing (default: true)"}},required:["source_path","destination_path"]},permission:{category:"write",allowInAskMode:false},async function({source_path:a,destination_path:e,overwrite:t=false,create_dirs:s=true}){if(!a||!e)return JSON.stringify(X("rename_file","error","Missing required parameters: source_path, destination_path",{error:"source_path and destination_path are required"}));let n=Ue(a),r=Ue(e),i=Le(n),o=Le(r),l=st();if(!Ht(n)||!Ht(r))return JSON.stringify(X("rename_file","error","Path is outside workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:`${n} -> ${r}`,error:"Path is outside workspace"}));if(n===l||r===l)return JSON.stringify(X("rename_file","error","Refusing to rename workspace root",{file_path:n}));try{await ce__default.lstat(n);}catch{return JSON.stringify(X("rename_file","error",`Source not found: ${i}`,{file_path:n,error:"Source not found"}))}let c=await ce__default.lstat(r).catch(()=>null);if(c&&!t)return JSON.stringify(X("rename_file","error",`Destination already exists: ${o}`,{file_path:r,error:"Destination already exists"}));try{return c&&t&&await ce__default.rm(r,{recursive:!0,force:!0}),s&&await ce__default.mkdir(te__default.dirname(r),{recursive:!0}),await ce__default.rename(n,r),JSON.stringify(X("rename_file","success",`Renamed: ${i} \u2192 ${o}`,{file_path:r,verify_hint:`Use "list_directory ${te__default.dirname(o)}" to verify.`,metadata:{from:n,to:r}}))}catch(u){return JSON.stringify(X("rename_file","error",`Failed to rename: ${i}`,{file_path:n,error:u.message}))}}},Ub={name:"apply_patch",description:"Apply a unified diff patch (git apply style)",parameters:{type:"object",properties:{patch:{type:"string",description:"Unified diff patch content"},strip:{type:"number",description:"Strip leading path components (git apply -p, default: 0)"},reverse:{type:"boolean",description:"Apply patch in reverse (default: false)"}},required:["patch"]},permission:{category:"write",allowInAskMode:false},async function({patch:a,strip:e=0,reverse:t=false}){if(!a||typeof a!="string")return JSON.stringify(X("apply_patch","error","Missing required parameter: patch",{error:"patch is required"}));if(!Number.isInteger(e)||e<0||e>10)return JSON.stringify(X("apply_patch","error","Invalid strip value (must be an integer between 0 and 10)",{error:"Invalid strip value"}));if(Buffer.byteLength(a,"utf8")>tp)return JSON.stringify(X("apply_patch","error",`Patch too large (max ${tp} bytes)`,{error:"Patch too large"}));let s=a.split(`
862
+ `).filter(c=>c.startsWith("+++ ")||c.startsWith("--- "));for(let c of s){let u=c.slice(4).trim();if(u==="/dev/null"||u.toLowerCase()==="nul")continue;let d=u.replace(/^a\//,"").replace(/^b\//,"");if(d.startsWith("/")||/^[A-Za-z]:[\\/]/.test(d))return JSON.stringify(X("apply_patch","error","Patch contains absolute paths",{error:"Absolute paths are not allowed in patch"}));if(d.split(/[\\/]+/).includes(".."))return JSON.stringify(X("apply_patch","error","Patch contains path traversal",{error:"Path traversal is not allowed in patch"}))}let n=st(),{repoRoot:r,error:i}=await Ts(n);if(!r)return JSON.stringify(X("apply_patch","error",`Not a git repository: ${i||"unknown error"}`,{error:"Not a git repository"}));let o=await ce__default.mkdtemp(te__default.join(In__default.tmpdir(),"neox-patch-")),l=te__default.join(o,"apply.patch");try{await ce__default.writeFile(l,a,"utf8");let c=["apply"];e>0&&c.push(`-p${e}`),t&&c.push("--reverse");let u=await We("git",[...c,"--check",l],r);if(u.exitCode!==0){let p=[u.stdout,u.stderr].filter(Boolean).join(`
863
863
  `).trim();return JSON.stringify(X("apply_patch","error","Patch check failed",{error:p||"Patch check failed",verify_hint:"Ensure the patch applies cleanly to the current workspace state."}))}let d=await We("git",[...c,"--whitespace=nowarn",l],r);if(d.exitCode!==0){let p=[d.stdout,d.stderr].filter(Boolean).join(`
864
- `).trim();return JSON.stringify(X("apply_patch","error","Patch apply failed",{error:p||"Patch apply failed"}))}return JSON.stringify(X("apply_patch","success","Patch applied successfully",{verify_hint:"Use git diff or readfile to verify changes."}))}catch(c){return JSON.stringify(X("apply_patch","error","Patch apply failed",{error:c.message}))}finally{await ce__default.rm(o,{recursive:true,force:true}).catch(()=>{});}}},ap=process.env.NEOX_SANDBOX==="on";function lp(a){ap=a;}var Ub={name:"execute_shell",description:`Execute shell command with smart background process management.
864
+ `).trim();return JSON.stringify(X("apply_patch","error","Patch apply failed",{error:p||"Patch apply failed"}))}return JSON.stringify(X("apply_patch","success","Patch applied successfully",{verify_hint:"Use git diff or readfile to verify changes."}))}catch(c){return JSON.stringify(X("apply_patch","error","Patch apply failed",{error:c.message}))}finally{await ce__default.rm(o,{recursive:true,force:true}).catch(()=>{});}}},ap=process.env.NEOX_SANDBOX==="on";function lp(a){ap=a;}var Wb={name:"execute_shell",description:`Execute shell command with smart background process management.
865
865
 
866
866
  \u{1F525} CRITICAL - Background Process Behavior:
867
867
  - background=true: For LONG-RUNNING processes (npm run dev, servers, watch modes)
@@ -889,7 +889,7 @@ For searching file CONTENTS, use search instead.`,parameters:{type:"object",prop
889
889
  - Use /processes to list all running background processes
890
890
  - Use /kill <pid> to stop a background process before retrying`,parameters:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},background:{type:"boolean",description:"Run in background. Use TRUE for: npm run dev, servers, watch modes, npm install (large projects), db migrations, docker builds. Use FALSE for: quick commands like ls, git status, cat. Default: false"}},required:["command"]},async function({command:a,background:e=false},t){if(ap){let u=["ls","pwd","echo","cat","grep","find","wc","head","tail"],d=a.trim().split(" ")[0];if(!u.includes(d))return `\u2717 \u6C99\u7BB1\u6A21\u5F0F\uFF1A\u4E0D\u5141\u8BB8\u6267\u884C\u547D\u4EE4: ${d}
891
891
  \u5141\u8BB8\u7684\u547D\u4EE4: ${u.join(", ")}
892
- \u63D0\u793A: \u4F7F\u7528 /sandbox off \u5173\u95ED\u6C99\u7BB1\u6A21\u5F0F`}let n=st(),r=t?.signal,i=a.trim().endsWith("&"),o=a.includes("|");e&&(i||o)&&(we.warn("SHELL","\u68C0\u6D4B\u5230\u540E\u53F0\u6A21\u5F0F\u4E0B\u4F7F\u7528\u4E86 '&' \u6216\u7BA1\u9053\u7B26\u53F7\uFF0C\u8FD9\u53EF\u80FD\u5BFC\u81F4\u975E\u9884\u671F\u884C\u4E3A"),i&&we.info("SHELL","\u63D0\u793A: background=true \u53C2\u6570\u5DF2\u7ECF\u5904\u7406\u540E\u53F0\u8FD0\u884C\uFF0C\u65E0\u9700\u5728\u547D\u4EE4\u672B\u5C3E\u6DFB\u52A0 '&'"),o&&we.warn("SHELL","\u8B66\u544A: \u540E\u53F0\u6A21\u5F0F\u4E0B\u4F7F\u7528\u7BA1\u9053\u53EF\u80FD\u5BFC\u81F4\u8F93\u51FA\u622A\u65AD\u6216\u8FDB\u7A0B\u610F\u5916\u9000\u51FA"));let c=await _b(a,e,n,r);if(c){if(c.background&&c.pid){Ke.processManager.get(c.pid)||Ke.processManager.register({pid:c.pid,command:a,cwd:n,background:true});let u=Ke.processManager.getBackgroundRunning().length;return c.output.replace(/当前后台进程总数:\s*\d+/,`\u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: ${u}`)}return c.output}if(e){let u=a.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,""),d=Ke.processManager.getBackgroundRunning().find(p=>p.command.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,"")===u);if(d){let p=Math.floor((Date.now()-d.startTime.getTime())/1e3),h=Ke.processManager.getBackgroundRunning().length;return `\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
892
+ \u63D0\u793A: \u4F7F\u7528 /sandbox off \u5173\u95ED\u6C99\u7BB1\u6A21\u5F0F`}let n=st(),r=t?.signal,i=a.trim().endsWith("&"),o=a.includes("|");e&&(i||o)&&(we.warn("SHELL","\u68C0\u6D4B\u5230\u540E\u53F0\u6A21\u5F0F\u4E0B\u4F7F\u7528\u4E86 '&' \u6216\u7BA1\u9053\u7B26\u53F7\uFF0C\u8FD9\u53EF\u80FD\u5BFC\u81F4\u975E\u9884\u671F\u884C\u4E3A"),i&&we.info("SHELL","\u63D0\u793A: background=true \u53C2\u6570\u5DF2\u7ECF\u5904\u7406\u540E\u53F0\u8FD0\u884C\uFF0C\u65E0\u9700\u5728\u547D\u4EE4\u672B\u5C3E\u6DFB\u52A0 '&'"),o&&we.warn("SHELL","\u8B66\u544A: \u540E\u53F0\u6A21\u5F0F\u4E0B\u4F7F\u7528\u7BA1\u9053\u53EF\u80FD\u5BFC\u81F4\u8F93\u51FA\u622A\u65AD\u6216\u8FDB\u7A0B\u610F\u5916\u9000\u51FA"));let c=await Rb(a,e,n,r);if(c){if(c.background&&c.pid){Ke.processManager.get(c.pid)||Ke.processManager.register({pid:c.pid,command:a,cwd:n,background:true});let u=Ke.processManager.getBackgroundRunning().length;return c.output.replace(/当前后台进程总数:\s*\d+/,`\u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: ${u}`)}return c.output}if(e){let u=a.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,""),d=Ke.processManager.getBackgroundRunning().find(p=>p.command.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,"")===u);if(d){let p=Math.floor((Date.now()-d.startTime.getTime())/1e3),h=Ke.processManager.getBackgroundRunning().length;return `\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
893
893
  \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${n}
894
894
  \u25B8 \u6267\u884C\u547D\u4EE4: ${a}
895
895
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
@@ -989,26 +989,26 @@ ${u.stderr?`\u25E6 \u9519\u8BEF\u4FE1\u606F:
989
989
  ${u.stderr}
990
990
 
991
991
  `:""}
992
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}}},Wb={name:"show_tree",description:"Display directory tree structure",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path (default: current directory)"},max_depth:{type:"number",description:"Maximum depth to traverse (default: 3)"}}},async function({directory:a=".",max_depth:e=3}){try{let t=Ue(a),s=[`${Le(t)}/
992
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}}},qb={name:"show_tree",description:"Display directory tree structure",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path (default: current directory)"},max_depth:{type:"number",description:"Maximum depth to traverse (default: 3)"}}},async function({directory:a=".",max_depth:e=3}){try{let t=Ue(a),s=[`${Le(t)}/
993
993
  `];async function n(r,i="",o=0){if(o>=e)return;let u=(await ce__default.readdir(r,{withFileTypes:!0})).filter(d=>!d.name.startsWith(".")).sort((d,p)=>d.isDirectory()&&!p.isDirectory()?-1:!d.isDirectory()&&p.isDirectory()?1:d.name.localeCompare(p.name));for(let d=0;d<u.length;d++){let p=u[d],h=d===u.length-1,g=h?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=h?" ":"\u2502 ";if(p.isDirectory())s.push(`${i}${g}${p.name}/`),await n(te__default.join(r,p.name),i+f,o+1);else {let b=await ce__default.stat(te__default.join(r,p.name)),y=b.size<1024?`${b.size}B`:b.size<1024*1024?`${(b.size/1024).toFixed(1)}KB`:`${(b.size/(1024*1024)).toFixed(1)}MB`;s.push(`${i}${g}${p.name} (${y})`);}}}return await n(t),s.join(`
994
- `)}catch(t){return `\u2717 \u663E\u793A\u76EE\u5F55\u6811\u5931\u8D25: ${t.message}`}}},qb={name:"git_status",description:"Show git status (short by default)",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},short:{type:"boolean",description:"Use short format (default: true)"}}},permission:{category:"read",allowInAskMode:true},async function({path:a=".",short:e=true}){let t=Ue(a);if(!Ht(t))return JSON.stringify(ve("git_status","error","git status failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(ve("git_status","error",`git status failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let r=["status"];e&&r.push("-sb");let i=await We("git",r,s),o=[i.stdout,i.stderr].filter(Boolean).join(`
995
- `).trim();return i.exitCode!==0?JSON.stringify(ve("git_status","error","git status failed",o||void 0,{error:o||"git status failed"})):JSON.stringify(ve("git_status","success",o?"git status ok":"git status clean",o||"\u2713 clean"))}},zb={name:"git_diff",description:"Show git diff",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},staged:{type:"boolean",description:"Show staged diff (default: false)"},file_path:{type:"string",description:"Limit diff to a specific file"}}},permission:{category:"read",allowInAskMode:true},async function({path:a=".",staged:e=false,file_path:t}){let s=Ue(a);if(!Ht(s))return JSON.stringify(ve("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:r}=await Ts(s);if(!n)return JSON.stringify(ve("git_diff","error",`git diff failed: ${r||"not a git repository"}`,void 0,{error:r||"not a git repository"}));let i=["diff"];if(e&&i.push("--staged"),t){let c=Ue(t);if(!Ht(c))return JSON.stringify(ve("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let u=te__default.relative(n,c);if(u.startsWith("..")||te__default.isAbsolute(u))return JSON.stringify(ve("git_diff","error","git diff failed: file outside repo",void 0,{error:"file outside repo"}));i.push("--",u);}let o=await We("git",i,n),l=[o.stdout,o.stderr].filter(Boolean).join(`
996
- `).trim();return o.exitCode!==0?JSON.stringify(ve("git_diff","error","git diff failed",l||void 0,{error:l||"git diff failed"})):JSON.stringify(ve("git_diff","success",l?"git diff ok":"no diff",l||""))}},Hb={name:"git_blame",description:"Show git blame for a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"File path to blame (required)"},start_line:{type:"number",description:"Start line (1-based)"},end_line:{type:"number",description:"End line (1-based)"}},required:["file_path"]},permission:{category:"read",allowInAskMode:true},async function({file_path:a,start_line:e,end_line:t}){if(!a)return JSON.stringify(ve("git_blame","error","git blame failed: file_path is required",void 0,{error:"file_path is required"}));let s=Ue(a);if(!Ht(s))return JSON.stringify(ve("git_blame","error","git blame failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:r}=await Ts(te__default.dirname(s));if(!n)return JSON.stringify(ve("git_blame","error",`git blame failed: ${r||"not a git repository"}`,void 0,{error:r||"not a git repository"}));let i=e&&t?`${e},${t}`:void 0,o=te__default.relative(n,s);if(o.startsWith("..")||te__default.isAbsolute(o))return JSON.stringify(ve("git_blame","error","git blame failed: file outside repo",void 0,{error:"file outside repo"}));let l=["blame","--",o];i&&l.splice(1,0,"-L",i);let c=await We("git",l,n),u=[c.stdout,c.stderr].filter(Boolean).join(`
997
- `).trim();return c.exitCode!==0?JSON.stringify(ve("git_blame","error","git blame failed",u||void 0,{error:u||"git blame failed"})):JSON.stringify(ve("git_blame","success","git blame ok",u||""))}},Jb={name:"git_branch_list",description:"List git branches",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},all:{type:"boolean",description:"Include remote branches (default: false)"}}},permission:{category:"read",allowInAskMode:true},async function({path:a=".",all:e=false}){let t=Ue(a);if(!Ht(t))return JSON.stringify(ve("git_branch_list","error","git branch failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(ve("git_branch_list","error",`git branch failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let r=["branch","--list"];e&&r.push("--all");let i=await We("git",r,s),o=[i.stdout,i.stderr].filter(Boolean).join(`
994
+ `)}catch(t){return `\u2717 \u663E\u793A\u76EE\u5F55\u6811\u5931\u8D25: ${t.message}`}}},zb={name:"git_status",description:"Show git status (short by default)",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},short:{type:"boolean",description:"Use short format (default: true)"}}},permission:{category:"read",allowInAskMode:true},async function({path:a=".",short:e=true}){let t=Ue(a);if(!Ht(t))return JSON.stringify(ve("git_status","error","git status failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(ve("git_status","error",`git status failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let r=["status"];e&&r.push("-sb");let i=await We("git",r,s),o=[i.stdout,i.stderr].filter(Boolean).join(`
995
+ `).trim();return i.exitCode!==0?JSON.stringify(ve("git_status","error","git status failed",o||void 0,{error:o||"git status failed"})):JSON.stringify(ve("git_status","success",o?"git status ok":"git status clean",o||"\u2713 clean"))}},Hb={name:"git_diff",description:"Show git diff",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},staged:{type:"boolean",description:"Show staged diff (default: false)"},file_path:{type:"string",description:"Limit diff to a specific file"}}},permission:{category:"read",allowInAskMode:true},async function({path:a=".",staged:e=false,file_path:t}){let s=Ue(a);if(!Ht(s))return JSON.stringify(ve("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:r}=await Ts(s);if(!n)return JSON.stringify(ve("git_diff","error",`git diff failed: ${r||"not a git repository"}`,void 0,{error:r||"not a git repository"}));let i=["diff"];if(e&&i.push("--staged"),t){let c=Ue(t);if(!Ht(c))return JSON.stringify(ve("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let u=te__default.relative(n,c);if(u.startsWith("..")||te__default.isAbsolute(u))return JSON.stringify(ve("git_diff","error","git diff failed: file outside repo",void 0,{error:"file outside repo"}));i.push("--",u);}let o=await We("git",i,n),l=[o.stdout,o.stderr].filter(Boolean).join(`
996
+ `).trim();return o.exitCode!==0?JSON.stringify(ve("git_diff","error","git diff failed",l||void 0,{error:l||"git diff failed"})):JSON.stringify(ve("git_diff","success",l?"git diff ok":"no diff",l||""))}},Jb={name:"git_blame",description:"Show git blame for a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"File path to blame (required)"},start_line:{type:"number",description:"Start line (1-based)"},end_line:{type:"number",description:"End line (1-based)"}},required:["file_path"]},permission:{category:"read",allowInAskMode:true},async function({file_path:a,start_line:e,end_line:t}){if(!a)return JSON.stringify(ve("git_blame","error","git blame failed: file_path is required",void 0,{error:"file_path is required"}));let s=Ue(a);if(!Ht(s))return JSON.stringify(ve("git_blame","error","git blame failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:r}=await Ts(te__default.dirname(s));if(!n)return JSON.stringify(ve("git_blame","error",`git blame failed: ${r||"not a git repository"}`,void 0,{error:r||"not a git repository"}));let i=e&&t?`${e},${t}`:void 0,o=te__default.relative(n,s);if(o.startsWith("..")||te__default.isAbsolute(o))return JSON.stringify(ve("git_blame","error","git blame failed: file outside repo",void 0,{error:"file outside repo"}));let l=["blame","--",o];i&&l.splice(1,0,"-L",i);let c=await We("git",l,n),u=[c.stdout,c.stderr].filter(Boolean).join(`
997
+ `).trim();return c.exitCode!==0?JSON.stringify(ve("git_blame","error","git blame failed",u||void 0,{error:u||"git blame failed"})):JSON.stringify(ve("git_blame","success","git blame ok",u||""))}},Kb={name:"git_branch_list",description:"List git branches",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},all:{type:"boolean",description:"Include remote branches (default: false)"}}},permission:{category:"read",allowInAskMode:true},async function({path:a=".",all:e=false}){let t=Ue(a);if(!Ht(t))return JSON.stringify(ve("git_branch_list","error","git branch failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(ve("git_branch_list","error",`git branch failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let r=["branch","--list"];e&&r.push("--all");let i=await We("git",r,s),o=[i.stdout,i.stderr].filter(Boolean).join(`
998
998
  `).trim();if(i.exitCode!==0)return JSON.stringify(ve("git_branch_list","error","git branch failed",o||void 0,{error:o||"git branch failed"}));let l=o,c="git branches";if(!l){let u=await We("git",["symbolic-ref","--short","HEAD"],s),d=[u.stdout,u.stderr].filter(Boolean).join(`
999
- `).trim();u.exitCode===0&&d?(l=`* ${d} (current, no commits yet)`,c="git branches (no commits yet)"):(l="(no branches found)",c="git branches empty");}return JSON.stringify(ve("git_branch_list","success",c,l))}},Kb={name:"git_branch",description:"Create a git branch",parameters:{type:"object",properties:{name:{type:"string",description:"Branch name to create"},checkout:{type:"boolean",description:"Checkout after creation (default: false)"}},required:["name"]},permission:{category:"write",allowInAskMode:false},async function({name:a,checkout:e=false}){let t=st(),{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(X("git_branch","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));if(!a)return JSON.stringify(X("git_branch","error","Branch name is required (use git_branch_list to list branches)",{error:"name is required"}));let r=typeof a=="string"?a.trim():"",i=/^[A-Za-z0-9._\\/-]+$/.test(r);if(!r||!i||r.includes("..")||r.startsWith("/")||r.endsWith("/"))return JSON.stringify(X("git_branch","error","Invalid branch name",{error:"Invalid branch name"}));let l=await We("git",["branch",r],s);if(l.exitCode!==0){let c=[l.stdout,l.stderr].filter(Boolean).join(`
999
+ `).trim();u.exitCode===0&&d?(l=`* ${d} (current, no commits yet)`,c="git branches (no commits yet)"):(l="(no branches found)",c="git branches empty");}return JSON.stringify(ve("git_branch_list","success",c,l))}},Vb={name:"git_branch",description:"Create a git branch",parameters:{type:"object",properties:{name:{type:"string",description:"Branch name to create"},checkout:{type:"boolean",description:"Checkout after creation (default: false)"}},required:["name"]},permission:{category:"write",allowInAskMode:false},async function({name:a,checkout:e=false}){let t=st(),{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(X("git_branch","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));if(!a)return JSON.stringify(X("git_branch","error","Branch name is required (use git_branch_list to list branches)",{error:"name is required"}));let r=typeof a=="string"?a.trim():"",i=/^[A-Za-z0-9._\\/-]+$/.test(r);if(!r||!i||r.includes("..")||r.startsWith("/")||r.endsWith("/"))return JSON.stringify(X("git_branch","error","Invalid branch name",{error:"Invalid branch name"}));let l=await We("git",["branch",r],s);if(l.exitCode!==0){let c=[l.stdout,l.stderr].filter(Boolean).join(`
1000
1000
  `).trim();return JSON.stringify(X("git_branch","error","Failed to create branch",{error:c||"Failed to create branch"}))}if(e){let c=await We("git",["checkout",r],s);if(c.exitCode!==0){let u=[c.stdout,c.stderr].filter(Boolean).join(`
1001
- `).trim();return JSON.stringify(X("git_branch","error","Branch created but checkout failed",{error:u||"Checkout failed"}))}}return JSON.stringify(X("git_branch","success",e?`Branch created and checked out: ${r}`:`Branch created: ${r}`,{metadata:{branch:r,checkout:e}}))}},Vb={name:"git_commit",description:"Create a git commit",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"Run git add -A before commit (default: false)"}},required:["message"]},permission:{category:"write",allowInAskMode:false},async function({message:a,add_all:e=false}){let t=st(),{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(X("git_commit","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));let r=typeof a=="string"?a.trim():"";if(!r||r.length<3)return JSON.stringify(X("git_commit","error","Commit message is too short",{error:"Commit message is too short"}));if(e){let o=await We("git",["add","-A"],s);if(o.exitCode!==0){let l=[o.stdout,o.stderr].filter(Boolean).join(`
1001
+ `).trim();return JSON.stringify(X("git_branch","error","Branch created but checkout failed",{error:u||"Checkout failed"}))}}return JSON.stringify(X("git_branch","success",e?`Branch created and checked out: ${r}`:`Branch created: ${r}`,{metadata:{branch:r,checkout:e}}))}},Yb={name:"git_commit",description:"Create a git commit",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"Run git add -A before commit (default: false)"}},required:["message"]},permission:{category:"write",allowInAskMode:false},async function({message:a,add_all:e=false}){let t=st(),{repoRoot:s,error:n}=await Ts(t);if(!s)return JSON.stringify(X("git_commit","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));let r=typeof a=="string"?a.trim():"";if(!r||r.length<3)return JSON.stringify(X("git_commit","error","Commit message is too short",{error:"Commit message is too short"}));if(e){let o=await We("git",["add","-A"],s);if(o.exitCode!==0){let l=[o.stdout,o.stderr].filter(Boolean).join(`
1002
1002
  `).trim();return JSON.stringify(X("git_commit","error","git add -A failed",{error:l||"git add failed"}))}}let i=await We("git",["commit","-m",r],s);if(i.exitCode!==0){let o=[i.stdout,i.stderr].filter(Boolean).join(`
1003
- `).trim();return JSON.stringify(X("git_commit","error","git commit failed",{error:o||"git commit failed"}))}return JSON.stringify(X("git_commit","success",`Commit created: ${r}`,{metadata:{message:r}}))}};async function Yb(a){let e=ce__default.stat(te__default.join(a,"package.json")).then(()=>true).catch(()=>false),t=ce__default.stat(te__default.join(a,"pnpm-lock.yaml")).then(()=>true).catch(()=>false),s=ce__default.stat(te__default.join(a,"yarn.lock")).then(()=>true).catch(()=>false),n=ce__default.stat(te__default.join(a,"bun.lockb")).then(()=>true).catch(()=>false),r=ce__default.stat(te__default.join(a,"pyproject.toml")).then(()=>true).catch(()=>false),i=ce__default.stat(te__default.join(a,"pytest.ini")).then(()=>true).catch(()=>false),o=ce__default.stat(te__default.join(a,"go.mod")).then(()=>true).catch(()=>false),l=ce__default.stat(te__default.join(a,"Cargo.toml")).then(()=>true).catch(()=>false),c=ce__default.stat(te__default.join(a,"Makefile")).then(()=>true).catch(()=>false);return Promise.all([e,t,s,n,r,i,o,l,c]).then(([u,d,p,h,g,f,b,y,w])=>u?d?"pnpm":p?"yarn":h?"bun":"npm":g||f?"pytest":b?"go":y?"cargo":w?"make":null)}function Xb(a,e,t){switch(a){case "npm":case "pnpm":case "yarn":case "bun":return {command:a,args:["run",e==="test"?"test":e==="lint"?"lint":"format",...t]};case "pytest":return {command:"pytest",args:t};case "go":return e==="test"?{command:"go",args:["test","./...",...t]}:e==="lint"?{command:"golangci-lint",args:["run",...t]}:{command:"gofmt",args:["-w",...t]};case "cargo":return e==="test"?{command:"cargo",args:["test",...t]}:e==="lint"?{command:"cargo",args:["clippy","--",...t]}:{command:"cargo",args:["fmt",...t]};case "make":return {command:"make",args:[e,...t]};default:return {command:"npm",args:["run",e,...t]}}}async function hl(a,e,t){let s=Ue(t.cwd||".");if(!Ht(s))return JSON.stringify(Xt(a,"error","Command rejected: path outside workspace",{error:"cwd is outside workspace"}));if(t.extra_args!==void 0&&!Array.isArray(t.extra_args))return JSON.stringify(Xt(a,"error","Invalid extra_args: expected an array of strings",{error:"extra_args must be an array"}));let n=Array.isArray(t.extra_args)?t.extra_args.map(l=>String(l)):[],r=t.preset||await Yb(s),i=t.command,o=[];if(i){let l=Eb(i);if(!l.command)return JSON.stringify(Xt(a,"error","Invalid command",{error:"Command is empty"}));let c=new Set(["npm","pnpm","yarn","bun","pytest","go","cargo","make"]);if(!c.has(l.command))return JSON.stringify(Xt(a,"error","Command not allowed",{error:`Allowed commands: ${Array.from(c).join(", ")}`}));let u=l.args.concat(n),d=await We(l.command,u,s,{timeoutMs:t.timeout_ms||3e5}),p=[d.stdout,d.stderr].filter(Boolean).join(`
1004
- `),h=Fi(p,Zd),g=d.exitCode===0?`${a} succeeded (${d.durationMs}ms)`:`${a} failed with exit code ${d.exitCode}`;return JSON.stringify(Xt(a,d.exitCode===0?"success":"error",g,{error:d.exitCode===0?void 0:Fi(p,ep).text,metadata:{command:[l.command,...u].join(" "),exit_code:d.exitCode,duration_ms:d.durationMs,output_truncated:h.truncated}}))}if(r){let l=Xb(r,e,n);o=l.args;let c=await We(l.command,o,s,{timeoutMs:t.timeout_ms||3e5}),u=[c.stdout,c.stderr].filter(Boolean).join(`
1005
- `),d=Fi(u,Zd),p=c.exitCode===0?`${a} succeeded (${c.durationMs}ms)`:`${a} failed with exit code ${c.exitCode}`;return JSON.stringify(Xt(a,c.exitCode===0?"success":"error",p,{error:c.exitCode===0?void 0:Fi(u,ep).text,metadata:{command:[l.command,...o].join(" "),exit_code:c.exitCode,duration_ms:c.durationMs,output_truncated:d.truncated}}))}return JSON.stringify(Xt(a,"error","Unable to detect project type for command",{error:"No preset detected. Provide preset."}))}var Qb={name:"run_tests",description:"Run project tests with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(a){return hl("run_tests","test",a)}},Zb={name:"run_lint",description:"Run project lint with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(a){return hl("run_lint","lint",a)}},ev={name:"run_format",description:"Run project formatting with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(a){return hl("run_format","format",a)}},tv={name:"analyze_code",description:"Analyze code file structure and statistics",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to code file"}},required:["file_path"]},async function({file_path:a}){try{let e=Ue(a),s=(await ce__default.readFile(e,"utf-8")).split(`
1003
+ `).trim();return JSON.stringify(X("git_commit","error","git commit failed",{error:o||"git commit failed"}))}return JSON.stringify(X("git_commit","success",`Commit created: ${r}`,{metadata:{message:r}}))}};async function Xb(a){let e=ce__default.stat(te__default.join(a,"package.json")).then(()=>true).catch(()=>false),t=ce__default.stat(te__default.join(a,"pnpm-lock.yaml")).then(()=>true).catch(()=>false),s=ce__default.stat(te__default.join(a,"yarn.lock")).then(()=>true).catch(()=>false),n=ce__default.stat(te__default.join(a,"bun.lockb")).then(()=>true).catch(()=>false),r=ce__default.stat(te__default.join(a,"pyproject.toml")).then(()=>true).catch(()=>false),i=ce__default.stat(te__default.join(a,"pytest.ini")).then(()=>true).catch(()=>false),o=ce__default.stat(te__default.join(a,"go.mod")).then(()=>true).catch(()=>false),l=ce__default.stat(te__default.join(a,"Cargo.toml")).then(()=>true).catch(()=>false),c=ce__default.stat(te__default.join(a,"Makefile")).then(()=>true).catch(()=>false);return Promise.all([e,t,s,n,r,i,o,l,c]).then(([u,d,p,h,g,f,b,y,w])=>u?d?"pnpm":p?"yarn":h?"bun":"npm":g||f?"pytest":b?"go":y?"cargo":w?"make":null)}function Qb(a,e,t){switch(a){case "npm":case "pnpm":case "yarn":case "bun":return {command:a,args:["run",e==="test"?"test":e==="lint"?"lint":"format",...t]};case "pytest":return {command:"pytest",args:t};case "go":return e==="test"?{command:"go",args:["test","./...",...t]}:e==="lint"?{command:"golangci-lint",args:["run",...t]}:{command:"gofmt",args:["-w",...t]};case "cargo":return e==="test"?{command:"cargo",args:["test",...t]}:e==="lint"?{command:"cargo",args:["clippy","--",...t]}:{command:"cargo",args:["fmt",...t]};case "make":return {command:"make",args:[e,...t]};default:return {command:"npm",args:["run",e,...t]}}}async function hl(a,e,t){let s=Ue(t.cwd||".");if(!Ht(s))return JSON.stringify(Xt(a,"error","Command rejected: path outside workspace",{error:"cwd is outside workspace"}));if(t.extra_args!==void 0&&!Array.isArray(t.extra_args))return JSON.stringify(Xt(a,"error","Invalid extra_args: expected an array of strings",{error:"extra_args must be an array"}));let n=Array.isArray(t.extra_args)?t.extra_args.map(l=>String(l)):[],r=t.preset||await Xb(s),i=t.command,o=[];if(i){let l=Ib(i);if(!l.command)return JSON.stringify(Xt(a,"error","Invalid command",{error:"Command is empty"}));let c=new Set(["npm","pnpm","yarn","bun","pytest","go","cargo","make"]);if(!c.has(l.command))return JSON.stringify(Xt(a,"error","Command not allowed",{error:`Allowed commands: ${Array.from(c).join(", ")}`}));let u=l.args.concat(n),d=await We(l.command,u,s,{timeoutMs:t.timeout_ms||3e5}),p=[d.stdout,d.stderr].filter(Boolean).join(`
1004
+ `),h=Fi(p,Zd),g=d.exitCode===0?`${a} succeeded (${d.durationMs}ms)`:`${a} failed with exit code ${d.exitCode}`;return JSON.stringify(Xt(a,d.exitCode===0?"success":"error",g,{error:d.exitCode===0?void 0:Fi(p,ep).text,metadata:{command:[l.command,...u].join(" "),exit_code:d.exitCode,duration_ms:d.durationMs,output_truncated:h.truncated}}))}if(r){let l=Qb(r,e,n);o=l.args;let c=await We(l.command,o,s,{timeoutMs:t.timeout_ms||3e5}),u=[c.stdout,c.stderr].filter(Boolean).join(`
1005
+ `),d=Fi(u,Zd),p=c.exitCode===0?`${a} succeeded (${c.durationMs}ms)`:`${a} failed with exit code ${c.exitCode}`;return JSON.stringify(Xt(a,c.exitCode===0?"success":"error",p,{error:c.exitCode===0?void 0:Fi(u,ep).text,metadata:{command:[l.command,...o].join(" "),exit_code:c.exitCode,duration_ms:c.durationMs,output_truncated:d.truncated}}))}return JSON.stringify(Xt(a,"error","Unable to detect project type for command",{error:"No preset detected. Provide preset."}))}var Zb={name:"run_tests",description:"Run project tests with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(a){return hl("run_tests","test",a)}},ev={name:"run_lint",description:"Run project lint with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(a){return hl("run_lint","lint",a)}},tv={name:"run_format",description:"Run project formatting with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(a){return hl("run_format","format",a)}},sv={name:"analyze_code",description:"Analyze code file structure and statistics",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to code file"}},required:["file_path"]},async function({file_path:a}){try{let e=Ue(a),s=(await ce__default.readFile(e,"utf-8")).split(`
1006
1006
  `),n=s.length,r=s.filter(p=>p.trim()&&!p.trim().startsWith("//")).length,i=s.filter(p=>p.trim().startsWith("//")).length,o=n-r-i,l=s.filter(p=>p.trim().startsWith("import ")||p.trim().startsWith("from ")),c=s.filter(p=>p.trim().startsWith("function ")||p.trim().startsWith("async function")),u=s.filter(p=>p.trim().startsWith("class ")),d=[`\u2713 \u4EE3\u7801\u5206\u6790: ${a}
1007
1007
  `,"\u7EDF\u8BA1:",` \u603B\u884C\u6570: ${n}`,` \u4EE3\u7801\u884C: ${r}`,` \u6CE8\u91CA\u884C: ${i}`,` \u7A7A\u767D\u884C: ${o}`];return l.length>0&&(d.push(`
1008
1008
  \u5BFC\u5165 (${l.length} \u4E2A):`),l.slice(0,5).forEach(p=>d.push(` - ${p.trim()}`)),l.length>5&&d.push(` ... \u8FD8\u6709 ${l.length-5} \u4E2A\u5BFC\u5165`)),u.length>0&&(d.push(`
1009
1009
  \u7C7B\u5B9A\u4E49 (${u.length} \u4E2A):`),u.forEach(p=>d.push(` - ${p.trim()}`))),c.length>0&&(d.push(`
1010
1010
  \u51FD\u6570\u5B9A\u4E49 (${c.length} \u4E2A):`),c.slice(0,10).forEach(p=>d.push(` - ${p.trim()}`)),c.length>10&&d.push(` ... \u8FD8\u6709 ${c.length-10} \u4E2A\u51FD\u6570`)),d.join(`
1011
- `)}catch(e){return `\u2717 \u5206\u6790\u5931\u8D25: ${e.message}`}}},ml=["!**/node_modules/**","!**/.git/**","!**/dist/**","!**/build/**","!**/out/**","!**/.next/**","!**/coverage/**","!**/__pycache__/**","!**/target/**","!**/vendor/**"],dr=null,ns=null;async function np(a,e){try{if(a!=="rg"){if(!a||!Me__default.existsSync(a))return !1;Me__default.accessSync(a,Me__default.constants.X_OK);}return (await We(a,["--version"],e,{timeoutMs:2e3})).exitCode===0}catch{return false}}function sv(a,e){if(a===-1)return true;let t=(e||"").toLowerCase();return t.includes("ebadf")||t.includes("enoent")||t.includes("eacces")||t.includes("spawn")||t.includes("not found")||t.includes("permission denied")}async function gl(){if(ns!==null)return ns;let a=st();try{let{rgPath:t}=await import('@vscode/ripgrep');if(await np(t,a))return ns=t,we.info("SEARCH",`Using bundled ripgrep: ${t}`),ns;we.warn("SEARCH",`Bundled ripgrep path is invalid or not executable: ${t}`);}catch(t){we.warn("SEARCH",`Bundled ripgrep not available: ${t.message}`);}return await np("rg",a)?(ns="rg",we.info("SEARCH","Using system ripgrep"),ns):(ns=null,null)}async function nv(){return dr!==null||(dr=await gl()!==null,dr?we.info("SEARCH","ripgrep available"):we.warn("SEARCH","ripgrep not available, using fallback")),dr}function rv(a){let e=a.case_insensitive??true,t=[],s=(n,r,i)=>{if(!n.pattern||!n.pattern.trim())return;let o=(n.op||r).toLowerCase(),l=n.regex??i,c=n.case_insensitive??e;t.push({id:`q${t.length+1}`,pattern:n.pattern,op:o==="and"||o==="or"||o==="not"?o:r,regex:l,caseInsensitive:c});};if((a.pattern||a.query)&&s({pattern:a.pattern||a.query||"",op:a.op},"or",true),Array.isArray(a.keywords))for(let n of a.keywords)s({pattern:n},"or",false);if(Array.isArray(a.queries))for(let n of a.queries)s(n,"or",n.regex??true);return t}var iv={name:"search",description:`\u3010\u5168\u5C40\u641C\u7D22\u3011\u652F\u6301\u591A\u5173\u952E\u8BCD\u3001\u591A\u67E5\u8BE2\u3001\u8DE8\u76EE\u5F55\u81EA\u52A8\u5B9A\u4F4D\u3002
1011
+ `)}catch(e){return `\u2717 \u5206\u6790\u5931\u8D25: ${e.message}`}}},ml=["!**/node_modules/**","!**/.git/**","!**/dist/**","!**/build/**","!**/out/**","!**/.next/**","!**/coverage/**","!**/__pycache__/**","!**/target/**","!**/vendor/**"],dr=null,ns=null;async function np(a,e){try{if(a!=="rg"){if(!a||!Me__default.existsSync(a))return !1;Me__default.accessSync(a,Me__default.constants.X_OK);}return (await We(a,["--version"],e,{timeoutMs:2e3})).exitCode===0}catch{return false}}function nv(a,e){if(a===-1)return true;let t=(e||"").toLowerCase();return t.includes("ebadf")||t.includes("enoent")||t.includes("eacces")||t.includes("spawn")||t.includes("not found")||t.includes("permission denied")}async function gl(){if(ns!==null)return ns;let a=st();try{let{rgPath:t}=await import('@vscode/ripgrep');if(await np(t,a))return ns=t,we.info("SEARCH",`Using bundled ripgrep: ${t}`),ns;we.warn("SEARCH",`Bundled ripgrep path is invalid or not executable: ${t}`);}catch(t){we.warn("SEARCH",`Bundled ripgrep not available: ${t.message}`);}return await np("rg",a)?(ns="rg",we.info("SEARCH","Using system ripgrep"),ns):(ns=null,null)}async function rv(){return dr!==null||(dr=await gl()!==null,dr?we.info("SEARCH","ripgrep available"):we.warn("SEARCH","ripgrep not available, using fallback")),dr}function iv(a){let e=a.case_insensitive??true,t=[],s=(n,r,i)=>{if(!n.pattern||!n.pattern.trim())return;let o=(n.op||r).toLowerCase(),l=n.regex??i,c=n.case_insensitive??e;t.push({id:`q${t.length+1}`,pattern:n.pattern,op:o==="and"||o==="or"||o==="not"?o:r,regex:l,caseInsensitive:c});};if((a.pattern||a.query)&&s({pattern:a.pattern||a.query||"",op:a.op},"or",true),Array.isArray(a.keywords))for(let n of a.keywords)s({pattern:n},"or",false);if(Array.isArray(a.queries))for(let n of a.queries)s(n,"or",n.regex??true);return t}var ov={name:"search",description:`\u3010\u5168\u5C40\u641C\u7D22\u3011\u652F\u6301\u591A\u5173\u952E\u8BCD\u3001\u591A\u67E5\u8BE2\u3001\u8DE8\u76EE\u5F55\u81EA\u52A8\u5B9A\u4F4D\u3002
1012
1012
 
1013
1013
  \u{1F525} \u6781\u7B80\u7528\u6CD5\uFF1A
1014
1014
  search(pattern="\u767B\u5F55") \u2192 \u5168\u5C40\u5185\u5BB9\u641C\u7D22
@@ -1024,17 +1024,17 @@ search(mode="files", pattern="*.ts") \u2192 \u6587\u4EF6\u540D\u641C\u7D22
1024
1024
  \u8F93\u51FA\u7279\u70B9:
1025
1025
  - \u6BCF\u6761\u7ED3\u679C\u5E26 [\u6A21\u5757] \u524D\u7F00
1026
1026
  - \u663E\u793A\u6A21\u5757\u5206\u5E03\u7EDF\u8BA1
1027
- - \u63D0\u4F9B readfile \u6279\u91CF\u8BFB\u53D6\u63D0\u793A`,parameters:{type:"object",properties:{pattern:{type:"string",description:'\u641C\u7D22\u6A21\u5F0F (\u9ED8\u8BA4\u6B63\u5219)\u3002\u793A\u4F8B: "error", "\u767B\u5F55", "function\\s+\\w+"'},query:{type:"string",description:"pattern \u7684\u522B\u540D"},keywords:{type:"array",items:{type:"string"},description:"\u591A\u5173\u952E\u8BCD OR \u641C\u7D22 (\u5B57\u9762\u91CF\u5339\u914D)"},queries:{type:"array",items:{type:"object",properties:{pattern:{type:"string"},op:{type:"string",enum:["and","or","not"]},regex:{type:"boolean"},case_insensitive:{type:"boolean"}},required:["pattern"]},description:"\u9AD8\u7EA7\u591A\u67E5\u8BE2 (\u652F\u6301 and/or/not)"},op:{type:"string",enum:["and","or","not"],description:"pattern \u7684\u903B\u8F91\u64CD\u4F5C (\u9ED8\u8BA4 or)"},mode:{type:"string",enum:["content","files"],description:"\u641C\u7D22\u6A21\u5F0F: \u5185\u5BB9\u641C\u7D22\u6216\u6587\u4EF6\u540D\u641C\u7D22 (\u9ED8\u8BA4: content)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u53EF\u9009\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55)"},recursive:{type:"boolean",description:"\u9012\u5F52\u5B50\u76EE\u5F55 (\u53EF\u9009\uFF0C\u76EE\u5F55\u9ED8\u8BA4 true\uFF0C\u6587\u4EF6\u9ED8\u8BA4 false)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u7C7B\u578B\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,jsx,ts,tsx}")'},include_hidden:{type:"boolean",description:"\u5305\u542B\u9690\u85CF\u6587\u4EF6 (\u9ED8\u8BA4: false)"},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: true)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"},count_only:{type:"boolean",description:"\u4EC5\u8FD4\u56DE\u8BA1\u6570 (\u5FEB\u901F\u4E86\u89E3\u5339\u914D\u5206\u5E03)"}}},async function({pattern:a,query:e,keywords:t,queries:s,op:n,mode:r="content",path:i,recursive:o,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:d=2,max_matches:p=200,count_only:h=false},g){try{let f=Date.now();we.debug("SEARCH",`>>> searchTool.execute START, pattern=${a||e||t?.join(",")}`);let b=g?.signal,y=()=>{if(b?.aborted){let B=new Error("Operation cancelled");throw B.name="AbortError",B}},w=200,C=async()=>{await new Promise(B=>setImmediate(B));},T=Ue(i||"."),_="workspace",M=st();if(i&&te__default.isAbsolute(i))_="absolute";else if(i&&!Me__default.existsSync(T)){let B=M,re=null;for(;;){let V=te__default.resolve(B,i);if(Me__default.existsSync(V)){re=V;break}let pe=te__default.dirname(B);if(pe===B)break;B=pe;}re&&(T=re,_="ancestor");}let F=Le(T);y();let x;try{x=await ce__default.stat(T);}catch(B){return JSON.stringify(ve("search","error",`search failed: ${B.message}`,void 0,{error:B.message}))}let R=x.isDirectory(),j=o!==void 0?o:R,v=rv({pattern:a,query:e,keywords:t,queries:s,op:n,case_insensitive:u});if(y(),v.length===0)return JSON.stringify(ve("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let E=v.filter(B=>B.op!=="not"),L=v.filter(B=>B.op==="and"),I=v.filter(B=>B.op==="or"),A=v.filter(B=>B.op==="not");if(E.length===0)return JSON.stringify(ve("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let O=v.filter(B=>B.regex).map(B=>{try{return new RegExp(B.pattern),null}catch(re){return `${B.pattern}: ${re.message}`}}).filter(B=>!!B);if(O.length>0)return JSON.stringify(ve("search","error",`search failed: invalid regex (${O[0]})`,void 0,{error:`Invalid regex: ${O.join("; ")}`}));let $=[];I.length>0&&$.push(I.map(B=>B.pattern).join(" OR ")),L.length>0&&$.push(`AND ${L.map(B=>B.pattern).join(" + ")}`),A.length>0&&$.push(`NOT ${A.map(B=>B.pattern).join(" + ")}`);let P=$.join(" ");we.debug("SEARCH",`>>> Before isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let N=await nv();we.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let D=Math.min(200,Math.max(80,d*4+40));if(we.info("SEARCH",`Strategy: ${N?"ripgrep":"fallback"}`),!N)return JSON.stringify(ve("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
1027
+ - \u63D0\u4F9B readfile \u6279\u91CF\u8BFB\u53D6\u63D0\u793A`,parameters:{type:"object",properties:{pattern:{type:"string",description:'\u641C\u7D22\u6A21\u5F0F (\u9ED8\u8BA4\u6B63\u5219)\u3002\u793A\u4F8B: "error", "\u767B\u5F55", "function\\s+\\w+"'},query:{type:"string",description:"pattern \u7684\u522B\u540D"},keywords:{type:"array",items:{type:"string"},description:"\u591A\u5173\u952E\u8BCD OR \u641C\u7D22 (\u5B57\u9762\u91CF\u5339\u914D)"},queries:{type:"array",items:{type:"object",properties:{pattern:{type:"string"},op:{type:"string",enum:["and","or","not"]},regex:{type:"boolean"},case_insensitive:{type:"boolean"}},required:["pattern"]},description:"\u9AD8\u7EA7\u591A\u67E5\u8BE2 (\u652F\u6301 and/or/not)"},op:{type:"string",enum:["and","or","not"],description:"pattern \u7684\u903B\u8F91\u64CD\u4F5C (\u9ED8\u8BA4 or)"},mode:{type:"string",enum:["content","files"],description:"\u641C\u7D22\u6A21\u5F0F: \u5185\u5BB9\u641C\u7D22\u6216\u6587\u4EF6\u540D\u641C\u7D22 (\u9ED8\u8BA4: content)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u53EF\u9009\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55)"},recursive:{type:"boolean",description:"\u9012\u5F52\u5B50\u76EE\u5F55 (\u53EF\u9009\uFF0C\u76EE\u5F55\u9ED8\u8BA4 true\uFF0C\u6587\u4EF6\u9ED8\u8BA4 false)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u7C7B\u578B\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,jsx,ts,tsx}")'},include_hidden:{type:"boolean",description:"\u5305\u542B\u9690\u85CF\u6587\u4EF6 (\u9ED8\u8BA4: false)"},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: true)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"},count_only:{type:"boolean",description:"\u4EC5\u8FD4\u56DE\u8BA1\u6570 (\u5FEB\u901F\u4E86\u89E3\u5339\u914D\u5206\u5E03)"}}},async function({pattern:a,query:e,keywords:t,queries:s,op:n,mode:r="content",path:i,recursive:o,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:d=2,max_matches:p=200,count_only:h=false},g){try{let f=Date.now();we.debug("SEARCH",`>>> searchTool.execute START, pattern=${a||e||t?.join(",")}`);let b=g?.signal,y=()=>{if(b?.aborted){let B=new Error("Operation cancelled");throw B.name="AbortError",B}},w=200,C=async()=>{await new Promise(B=>setImmediate(B));},T=Ue(i||"."),_="workspace",M=st();if(i&&te__default.isAbsolute(i))_="absolute";else if(i&&!Me__default.existsSync(T)){let B=M,re=null;for(;;){let V=te__default.resolve(B,i);if(Me__default.existsSync(V)){re=V;break}let pe=te__default.dirname(B);if(pe===B)break;B=pe;}re&&(T=re,_="ancestor");}let F=Le(T);y();let x;try{x=await ce__default.stat(T);}catch(B){return JSON.stringify(ve("search","error",`search failed: ${B.message}`,void 0,{error:B.message}))}let R=x.isDirectory(),j=o!==void 0?o:R,v=iv({pattern:a,query:e,keywords:t,queries:s,op:n,case_insensitive:u});if(y(),v.length===0)return JSON.stringify(ve("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let E=v.filter(B=>B.op!=="not"),L=v.filter(B=>B.op==="and"),I=v.filter(B=>B.op==="or"),A=v.filter(B=>B.op==="not");if(E.length===0)return JSON.stringify(ve("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let O=v.filter(B=>B.regex).map(B=>{try{return new RegExp(B.pattern),null}catch(re){return `${B.pattern}: ${re.message}`}}).filter(B=>!!B);if(O.length>0)return JSON.stringify(ve("search","error",`search failed: invalid regex (${O[0]})`,void 0,{error:`Invalid regex: ${O.join("; ")}`}));let $=[];I.length>0&&$.push(I.map(B=>B.pattern).join(" OR ")),L.length>0&&$.push(`AND ${L.map(B=>B.pattern).join(" + ")}`),A.length>0&&$.push(`NOT ${A.map(B=>B.pattern).join(" + ")}`);let P=$.join(" ");we.debug("SEARCH",`>>> Before isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let N=await rv();we.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let D=Math.min(200,Math.max(80,d*4+40));if(we.info("SEARCH",`Strategy: ${N?"ripgrep":"fallback"}`),!N)return JSON.stringify(ve("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
1028
1028
  Please report this issue.`,{error:"ripgrep not available"}));if(y(),r==="files"){let B=await(async()=>{if(!R)return [Le(T)];if(N){let H=await gl();if(!H)throw new Error("ripgrep not available (this should not happen)");let se=["--files"];c&&se.push("--hidden"),!j&&R&&se.push("--max-depth","1"),l&&se.push("-g",l),ml.forEach(de=>se.push("-g",de)),se.push("--",T);let be=await We(H,se,st(),{signal:b});if(be.exitCode!==0&&be.exitCode!==1)throw new Error(be.stderr||"rg files search failed");return be.stdout.split(`
1029
1029
  `).filter(Boolean).map(de=>{let Ae=te__default.isAbsolute(de)?te__default.resolve(de):te__default.resolve(st(),de);return Le(Ae)})}let S=l||"**/*",U=j?S:S.replace("**/","");return (await ip(U,{cwd:T,absolute:!0,dot:c,onlyFiles:!0,ignore:ml.map(H=>H.replace("!",""))})).map(H=>Le(H))})();y();let re=v.map(S=>{let U=S.regex?S.pattern:Qd(S.pattern),Z=S.caseInsensitive?"i":"";return {query:S,regex:new RegExp(U,Z)}}),V=[],pe=0;for(let S of B){y();let U=S,Z=re.map(Y=>({op:Y.query.op,hit:Y.regex.test(U)})),H=Z.some(Y=>Y.op==="or"&&Y.hit),se=Z.filter(Y=>Y.op==="and").every(Y=>Y.hit);!Z.some(Y=>Y.op==="not"&&Y.hit)&&(L.length===0||se)&&(I.length===0||H)&&V.push(S),pe++,pe%w===0&&await C();}let Re=[`\u2713 \u6587\u4EF6\u641C\u7D22: ${P}`,`\u25B8 \u8DEF\u5F84: ${F}${j?" (\u9012\u5F52)":""}${_==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",c?"\u25B8 \u5305\u542B\u9690\u85CF\u6587\u4EF6":"","",`\u627E\u5230 ${V.length} \u4E2A\u6587\u4EF6`,""].filter(S=>S!==""),ae=50;return V.slice(0,ae).forEach(S=>Re.push(` ${S}`)),V.length>ae&&Re.push(` ... \u8FD8\u6709 ${V.length-ae} \u4E2A\u6587\u4EF6`),JSON.stringify(ve("search","success",V.length>0?`search files "${P}" (${V.length} files)`:`search files "${P}" (no matches)`,Re.join(`
1030
- `),{metadata:{mode:"files",strategy:N?"rg":"glob",regex:v.some(S=>S.regex),case_insensitive:u,path:F,resolved_from:_,files:V,queries:v}}))}let G=new Map,q=new Map,oe=0,ue=A.map(B=>{let re=B.regex?B.pattern:Qd(B.pattern),V=B.caseInsensitive?"i":"";return new RegExp(re,V)}),Se=[];if(N){let B=await gl();if(!B)throw new Error("ripgrep not available (this should not happen)");for(let re of E){y();let V=["--json","--with-filename","--line-number","--column","-a"];V.push("-C",String(d)),re.caseInsensitive&&V.push("-i"),re.regex||V.push("-F"),c&&V.push("--hidden"),!j&&R&&V.push("--max-depth","1"),l&&V.push("-g",l),ml.forEach(H=>V.push("-g",H)),V.push("--",re.pattern,T);let pe=B,Re="",ae=0,S="",U=async H=>{let se=`${H} ${V.join(" ")}`;return Se.push(se),We(H,V,st(),{signal:b})};try{let H=await U(pe);Re=H.stdout,S=H.stderr||"",ae=H.exitCode;}catch(H){if(H?.name==="AbortError"||b?.aborted)throw H;S=H?.message||H?.stderr||String(H),ae=H?.exitCode||2;}if(ae!==0&&ae!==1&&pe!=="rg"&&sv(ae,S)){we.warn("SEARCH","Bundled ripgrep failed, retrying with system rg",{exitCode:ae,error:S,bundledPath:pe});try{let H=await U("rg");Re=H.stdout,S=H.stderr||"",ae=H.exitCode,pe="rg",(ae===0||ae===1)&&(ns="rg");}catch(H){if(H?.name==="AbortError"||b?.aborted)throw H;let se=H?.message||H?.stderr||String(H);S=`${S}
1030
+ `),{metadata:{mode:"files",strategy:N?"rg":"glob",regex:v.some(S=>S.regex),case_insensitive:u,path:F,resolved_from:_,files:V,queries:v}}))}let G=new Map,q=new Map,oe=0,ue=A.map(B=>{let re=B.regex?B.pattern:Qd(B.pattern),V=B.caseInsensitive?"i":"";return new RegExp(re,V)}),Se=[];if(N){let B=await gl();if(!B)throw new Error("ripgrep not available (this should not happen)");for(let re of E){y();let V=["--json","--with-filename","--line-number","--column","-a"];V.push("-C",String(d)),re.caseInsensitive&&V.push("-i"),re.regex||V.push("-F"),c&&V.push("--hidden"),!j&&R&&V.push("--max-depth","1"),l&&V.push("-g",l),ml.forEach(H=>V.push("-g",H)),V.push("--",re.pattern,T);let pe=B,Re="",ae=0,S="",U=async H=>{let se=`${H} ${V.join(" ")}`;return Se.push(se),We(H,V,st(),{signal:b})};try{let H=await U(pe);Re=H.stdout,S=H.stderr||"",ae=H.exitCode;}catch(H){if(H?.name==="AbortError"||b?.aborted)throw H;S=H?.message||H?.stderr||String(H),ae=H?.exitCode||2;}if(ae!==0&&ae!==1&&pe!=="rg"&&nv(ae,S)){we.warn("SEARCH","Bundled ripgrep failed, retrying with system rg",{exitCode:ae,error:S,bundledPath:pe});try{let H=await U("rg");Re=H.stdout,S=H.stderr||"",ae=H.exitCode,pe="rg",(ae===0||ae===1)&&(ns="rg");}catch(H){if(H?.name==="AbortError"||b?.aborted)throw H;let se=H?.message||H?.stderr||String(H);S=`${S}
1031
1031
  Fallback rg failed: ${se}`.trim(),ae=H?.exitCode||2;}}if(ae!==0&&ae!==1){let H=S?`
1032
1032
  Error: ${S}`:"",se=`
1033
1033
  Command: ${pe} ${V.join(" ")}`;throw new Error(`ripgrep failed (exit code ${ae})${H}${se}`)}let Z=0;for(let H of Re.split(`
1034
1034
  `)){if(y(),Z++,Z%w===0&&await C(),!H.trim())continue;let se;try{se=JSON.parse(H);}catch{continue}if(se.type==="summary"){let Os=se.data?.stats;Os&&typeof Os.searches=="number"&&(oe=Math.max(oe,Os.searches));continue}let be=se.type==="match",Y=se.type==="context";if(!be&&!Y)continue;let de=se.data,Ae=de?.path?.text,et=de?.line_number,An=de?.lines?.text,gs=Array.isArray(de?.submatches)?de.submatches[0]:void 0;if(!Ae||!et||typeof An!="string")continue;let Gc=An.replace(/\n$/,""),Ko=G.get(Ae)||new Map,En=Ko.get(et)||{line:Gc,queryIds:new Set};if(En.line=Gc,be){En.queryIds.add(re.id),En.column===void 0&&gs?.start!==void 0&&(En.column=gs.start+1);let Os=q.get(Ae)||new Set;Os.add(re.id),q.set(Ae,Os);}Ko.set(et,En),G.set(Ae,Ko);}}}let z=new Set(L.map(B=>B.id)),J=[],ie=0,K=0,xe=0,ee=[],fe=[],ne=0;for(let[B,re]of G.entries()){if(y(),ie>=p&&!h)break;ne++,ne%w===0&&await C();let V=q.get(B)||new Set,pe=!0;if(z.forEach(H=>{V.has(H)||(pe=!1);}),!pe)continue;let ae=Array.from(re.keys()).sort((H,se)=>H-se).filter(H=>{let se=re.get(H);return se?!ue.some(be=>be.test(se.line)):!1});if(ae.length===0)continue;K++,ie+=ae.length;let S=Le(B);if(ee.push({file:S,anchor_lines:ae.slice(0,20),num_lines:D}),h){J.push({file:B,matches:[],matchCount:ae.length});continue}y();let U=[];Array.from(re.keys()).sort((H,se)=>H-se).forEach(H=>{let se=re.get(H);if(!se)return;let be=ae.includes(H);if(U.push({lineNum:H,line:se.line,isMatch:be}),be&&fe.length<p){for(let Y of se.queryIds)if(fe.push({file:S,line:H,column:se.column,preview:se.line,queryId:Y}),fe.length>=p)break}}),J.push({file:B,matches:U,matchCount:ae.length});}J.sort((B,re)=>Le(B.file).localeCompare(Le(re.file)));let le=B=>{let V=Le(B).split(te__default.sep),pe=V.findIndex(Re=>["src","lib","app","core","packages"].includes(Re));return pe>=0&&pe+1<V.length?V[pe+1]:V[0]||"root"},Q=[`\u2713 \u641C\u7D22: ${P}`,`\u25B8 \u8DEF\u5F84: ${F}${j?" (\u9012\u5F52)":""}${_==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",u?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",N?"\u25B8 \u7B56\u7565: ripgrep":"\u25B8 \u7B56\u7565: fallback","","\u2501\u2501\u2501\u2501 \u7ED3\u679C\u6458\u8981 \u2501\u2501\u2501\u2501",oe>0?`\u6587\u4EF6: ${oe} \u5DF2\u641C\u7D22, ${K} \u6709\u5339\u914D`:`\u6587\u4EF6: ${K} \u6709\u5339\u914D`,`\u5339\u914D: ${ie}${ie>=p?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(B=>B!==""),Be=new Map,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=Le(re.file),pe=le(re.file);Q.push(` [${pe}] ${V}: ${re.matchCount}`);}}else {let B=0,re=100;for(let V of J){if(y(),xe>=p){Q.push(`
1035
1035
  ... \u8FD8\u6709\u66F4\u591A\u5339\u914D (\u5DF2\u8FBE ${p} \u4E0A\u9650)`);break}let pe=Le(V.file),Re=le(V.file);Q.push(`
1036
1036
  \u25B8 [${Re}] ${pe} (${V.matchCount} \u5904)`),Q.push("\u2500".repeat(50));let ae=-10;for(let S of V.matches){if(xe>=p)break;B++,B%re===0&&await C(),S.lineNum>ae+1&&ae>0&&Q.push(" \u2504\u2504\u2504");let U=S.isMatch?"\u25B6":" ";Q.push(`${U}${String(S.lineNum).padStart(5)} \u2502 ${S.line}`),ae=S.lineNum,S.isMatch&&xe++;}}}return J.length===0?(Q.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),Q.push(""),Q.push("\u{1F4A1} \u5EFA\u8BAE:"),Q.push(" - \u5C1D\u8BD5 case_insensitive: true"),Q.push(" - \u5C1D\u8BD5 recursive: true \u641C\u7D22\u5B50\u76EE\u5F55"),Q.push(" - \u4F7F\u7528 keywords \u6216 queries \u7EC4\u5408\u641C\u7D22"),Q.push(' - \u67E5\u6587\u4EF6\u540D\u8BF7\u7528 mode="files"')):ee.length>0&&(Q.push(""),Q.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),ee.slice(0,3).forEach(B=>{Q.push(` readfile(path="${B.file}", anchor_lines=[${B.anchor_lines.join(",")}], num_lines=${B.num_lines})`);})),JSON.stringify(ve("search","success",J.length>0?`search "${P}" (${ie} matches)`:`search "${P}" (no matches)`,Q.join(`
1037
- `),{metadata:{mode:"content",strategy:N?"rg":"fallback",regex:v.some(B=>B.regex),case_insensitive:u,path:F,resolved_from:_,queries:v,matches:fe,read_hints:ee,files_with_matches:K,command:Se.length>0?Se[0]:void 0}}))}catch(f){return JSON.stringify(ve("search","error",`search failed: ${f.message}`,void 0,{error:f.message}))}}},ov={name:Oi.name,description:Oi.description,parameters:Oi.parameters,permission:{category:"read",allowInAskMode:true},async function(a){return zd(a)}},av={name:"use_skill",description:`Execute a registered skill to get specialized instructions for a task.
1037
+ `),{metadata:{mode:"content",strategy:N?"rg":"fallback",regex:v.some(B=>B.regex),case_insensitive:u,path:F,resolved_from:_,queries:v,matches:fe,read_hints:ee,files_with_matches:K,command:Se.length>0?Se[0]:void 0}}))}catch(f){return JSON.stringify(ve("search","error",`search failed: ${f.message}`,void 0,{error:f.message}))}}},av={name:Oi.name,description:Oi.description,parameters:Oi.parameters,permission:{category:"read",allowInAskMode:true},async function(a){return zd(a)}},lv={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:
1040
1040
  - commit: Git commit workflow with best practices
@@ -1053,17 +1053,17 @@ To list all skills, use the /skills command.`}let i=await new Ni(ht).execute(e,t
1053
1053
  ${i.output}
1054
1054
 
1055
1055
  ---
1056
- \u26A0\uFE0F IMPORTANT: Now execute the above instructions step by step. Do not ask for confirmation unless the instructions explicitly require it.`:`\u274C Skill execution failed: ${i.error}`}},cp=[Ib,Ob,jb,Bb,Gb,Nb,$b,Fb,qb,zb,Hb,Jb,Kb,Vb,Qb,Zb,ev,Ub,Wb,_u,tv,iv,ua,da,pa,Nu,ov,Jd,av];async function un(a,e){e&&kb(e);let t=e?.capabilities??Ke.capabilities,s=Oe(),n=[...cp];if(a&&n.push($u(a)),s.webSearch?.enabled&&n.push(Ea),s.javaDebug?.enabled)try{let c=await Da(s.javaDebug?.jarPath);n.push(...c),we.info("TOOLS",`Java Debug \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){we.error("TOOLS",`Java Debug \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`),we.error("TOOLS","\u63D0\u793A: \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D JAR \u6587\u4EF6");}if(s.smartRead?.enabled!==false)try{let c=ll(a);n.push(...c),we.info("TOOLS",`readfile \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){we.error("TOOLS",`readfile \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`);}let r=typeof process<"u"&&process.type==="renderer";t?.terminal&&r&&n.push(...ni()),t?.editor&&r&&n.push(...ri());let i=xb(n,t),o=s.enabledTools||{},l=i.filter(c=>o[c.name]!==false);return Yd(l)}function ji(a){return {output_info:a,behavior:{type:"allow"}}}function up(a,e){return {output_info:e,behavior:{type:"reject_content",message:a}}}function lv(a){let e=a.match(/Error\s+(?:code\s+)?(\d{3})/i);if(e)return e[1];let t=a.match(/(\d{3}):\s*([^<\n]+)/);return t?t[1]:null}function cv(a){let e=a.match(/<title>[^|]*\|\s*\d{3}:\s*([^<]+)<\/title>/i);if(e)return e[1].trim();let t=a.match(/<h1[^>]*>(?:<[^>]+>)*([^<]+?(?:\s+\d{3})?)<\/(?:[^>]+>)*<\/h1>/i);if(t)return t[1].replace(/Error code\s+\d{3}/i,"").trim();let s=a.match(/Error\s+code\s+(\d{3})/i);if(s){let r=s[1];return {502:"Bad gateway",503:"Service unavailable",504:"Gateway timeout",520:"Unknown error",521:"Web server is down",522:"Connection timed out",523:"Origin is unreachable",524:"A timeout occurred"}[r]||"Server error"}let n=a.match(/<span[^>]*class="inline-block"[^>]*>([^<]+)<\/span>/i);return n?n[1].trim():null}function uv(a){let e=a.match(/truncate[^>]*>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})<\/span>/);if(e)return e[1];let t=a.match(/<title>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:null}function pr(a){return a.trim().startsWith("<!DOCTYPE html")||a.trim().startsWith("<html")||/<html[^>]*>/i.test(a)}function dv(a){let e=a.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function _s(a,e){let t=dv(a);if(t)try{let i=JSON.parse(t);if(i.error){let o=i.error,l=o.type||o.code||(e?`HTTP_${e}`:"API_ERROR"),c=o.message||"API error",u;if(o.type==="usage_limit_reached"){let d=o.resets_at?new Date(o.resets_at*1e3).toLocaleString():void 0,p=o.resets_in_seconds;if(p){let h=Math.floor(p/3600),g=Math.floor(p%3600/60);u=`Usage limit reached (${o.plan_type||"unknown"} plan). Resets in ${h}h ${g}m.`;}else d&&(u=`Usage limit reached (${o.plan_type||"unknown"} plan). Resets at ${d}.`);}return {code:l,message:c,detail:u}}}catch{}if(a.trim().startsWith("{"))try{let i=JSON.parse(a);if(i.error){let o=i.error;return {code:o.type||o.code||(e?`HTTP_${e}`:"API_ERROR"),message:o.message||"API error"}}}catch{}if(pr(a)){let i=lv(a)||String(e||"UNKNOWN"),o=cv(a)||"Server error",l=uv(a),c;return l&&(l.includes("cloudflare")?c=`The server (${l}) is protected by Cloudflare but is not responding.`:c=`The API server (${l}) is not responding. This may be a temporary issue with your API provider.`),{code:`HTTP_${i}`,message:o,detail:c}}let s=a.match(/OpenAI.*error:\s*(\d+)\s*-\s*(.*)/i);if(s){let i=s[1],o=s[2];if(pr(o)){let l=_s(o,parseInt(i,10));return {code:l.code,message:l.message,detail:l.detail}}return o=o.trim(),o.length>200&&(o=o.slice(0,200)+"..."),{code:`HTTP_${i}`,message:o}}let n=a.match(/Anthropic.*error:\s*(\d+)\s*-\s*(.*)/i);if(n){let i=n[1],o=n[2].trim();return o.length>200&&(o=o.slice(0,200)+"..."),{code:`HTTP_${i}`,message:o}}if(a.includes("ECONNREFUSED"))return {code:"NETWORK_ERROR",message:"Connection refused",detail:"Unable to connect to the API server. Please check your network connection."};if(a.includes("ETIMEDOUT")||a.includes("timeout"))return {code:"TIMEOUT",message:"Connection timeout",detail:"The request took too long to complete. Please try again."};if(a.includes("ENOTFOUND"))return {code:"DNS_ERROR",message:"Server not found",detail:"Could not resolve the API server address. Please check your API base URL."};if(/context.*window.*exceeded/i.test(a)||/maximum.*context.*length/i.test(a))return {code:"CONTEXT_EXCEEDED",message:"Context window exceeded",detail:"The conversation is too long. Please start a new session or use /compact."};if(/rate.*limit/i.test(a)||a.includes("429"))return {code:"RATE_LIMIT",message:"Rate limit exceeded",detail:"Too many requests. Please wait a moment before trying again."};if(a.includes("401")||/unauthorized/i.test(a))return {code:"AUTH_ERROR",message:"Authentication failed",detail:"Please check your API key in settings."};if(a.includes("403")||/forbidden/i.test(a))return {code:"FORBIDDEN",message:"Access denied",detail:"Your API key does not have permission for this operation."};let r=a;return r=r.replace(/^Error:\s*/i,""),r=r.replace(/^Request failed with status code\s+\d+:\s*/i,""),r.length>300&&(r=r.slice(0,300)+"..."),{code:e?`HTTP_${e}`:"UNKNOWN",message:r}}var Ce=class a extends Error{category;code;retryable;retryAfter;context;originalError;constructor(e){super(e.message),this.name="NeoxError",this.category=e.category,this.code=e.code,this.retryable=e.retryable,this.retryAfter=e.retryAfter,this.context=e.context,this.originalError=e.originalError,Error.captureStackTrace&&Error.captureStackTrace(this,a);}withContext(e){return new a({...this,context:{...this.context,...e}})}toJSON(){return {name:this.name,category:this.category,code:this.code,message:this.message,retryable:this.retryable,retryAfter:this.retryAfter,context:this.context,stack:this.stack}}};function Jt(a){if(!a)return;if(typeof a!="string")return typeof a=="number"&&a>0?Math.ceil(a*1e3):void 0;let e=a.trim(),t=e.match(/^(\d+(?:\.\d+)?)\s*ms$/i);if(t){let r=parseFloat(t[1]);return r>0?Math.ceil(r):void 0}let s=parseFloat(e);if(!isNaN(s)&&s>0)return Math.ceil(s*1e3);let n=new Date(e);if(!isNaN(n.getTime())){let r=n.getTime()-Date.now();return r>0?Math.ceil(r):void 0}}function pv(a){switch(a){case 502:return 3e3;case 503:return 5e3;case 504:return 2e3;default:return 2e3}}function Bi(a){if(!a)return;let e=a["retry-after"]||a["Retry-After"];if(e){let r=Jt(e);if(r)return r}let t=a["retry-after-ms"]||a["Retry-After-Ms"];if(t){let r=parseFloat(t);if(!isNaN(r)&&r>0)return Math.ceil(r)}let s=a["x-ratelimit-reset-requests"];if(s){let r=Jt(s);if(r)return r}let n=a["anthropic-ratelimit-requests-reset"];if(n){let r=new Date(n);if(!isNaN(r.getTime())){let i=r.getTime()-Date.now();return i>0?Math.ceil(i):void 0}}}function fl(a){return typeof a=="object"&&a!==null&&"message"in a&&typeof a.message=="string"}function dp(a){return [/context.*window.*exceeded/i,/context.*length.*exceeded/i,/maximum.*context.*length/i,/token.*limit.*exceeded/i,/input.*too.*long/i].some(t=>t.test(a))}function mv(a){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(a))}function gv(a){if(a){if(typeof a=="string")return a;if(typeof a=="object"){if(typeof a.error=="string")return a.error;if(a.error?.message)return a.error.message;if(a.message)return a.message}}}function ft(a){if(a instanceof Ce)return a;let e=a instanceof Error?a.message:String(a),t=a instanceof Error?a:void 0,s=fl(a)?a:void 0,r=(s?gv(s.response?.data):void 0)||e;if(s?.response?.status){let i=s.response.status,o=Bi(s.response.headers),l=s.response.headers?.["x-request-id"]||s.response.headers?.["cf-ray"];if(i===429){let c=s.response.data,u=c?.error?.type;return u==="usage_limit_reached"||u==="usage_not_included"?new Ce({category:"fatal_limit",code:"USAGE_LIMIT_REACHED",message:c?.error?.message||"Usage limit reached",retryable:false,context:{httpStatus:i,requestId:l},originalError:t}):new Ce({category:"retryable_http",code:`HTTP_${i}`,message:r,retryable:true,retryAfter:o,context:{httpStatus:i,requestId:l},originalError:t})}if(i===502||i===503||i===504){let c=r;if(pr(r)){let d=_s(r,i);c=d.message,d.detail&&(c+=`
1057
- `+d.detail);}let u=o||pv(i);return new Ce({category:"retryable_rate_limit",code:`PROXY_${i}`,message:c||`API \u4EE3\u7406\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528 (${i})`,retryable:true,retryAfter:u,context:{httpStatus:i,requestId:l,rawMessage:r},originalError:t})}if(i>=500){let c=r;if(pr(r)){let u=_s(r,i);c=u.message,u.detail&&(c+=`
1058
- `+u.detail);}return new Ce({category:"retryable_http",code:`HTTP_${i}`,message:c,retryable:true,retryAfter:o,context:{httpStatus:i,requestId:l,rawMessage:r},originalError:t})}if(i===401)return new Ce({category:"fatal_auth",code:"UNAUTHORIZED",message:r||"Authentication failed. Please check your API key.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===403)return new Ce({category:"fatal_auth",code:"FORBIDDEN",message:r||"Access denied. Please check your API permissions.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===400)return dp(e)?new Ce({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t}):r.includes("Upstream request failed")||r.includes("upstream")||r.includes("gateway")?new Ce({category:"retryable_http",code:"PROXY_UPSTREAM_FAILED",message:r||"Proxy upstream request failed",retryable:true,context:{httpStatus:i,requestId:l},originalError:t}):new Ce({category:"fatal_invalid",code:"INVALID_REQUEST",message:r,retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i>=400&&i<500)return new Ce({category:"fatal_invalid",code:`HTTP_${i}`,message:r,retryable:false,context:{httpStatus:i,requestId:l},originalError:t})}if(fl(a)){let i=a.code,o=a.name;if(i==="ERR_CANCELED"||o==="CanceledError"||o==="AbortError")return new Ce({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:t});if(i==="ECONNREFUSED"||i==="ENOTFOUND"||i==="ECONNRESET")return new Ce({category:"retryable_network",code:i,message:`Network error: ${e}`,retryable:true,originalError:t});if(i==="ETIMEDOUT"||i==="ESOCKETTIMEDOUT")return new Ce({category:"retryable_network",code:"TIMEOUT",message:`Connection timeout: ${e}`,retryable:true,originalError:t})}return a instanceof Error&&a.name==="AbortError"?new Ce({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:a}):fl(a)&&a.code==="STREAM_INCOMPLETE"?new Ce({category:"retryable_stream",code:"STREAM_INCOMPLETE",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,context:{toolName:a.toolName,rawMessage:e},originalError:t}):a?.code==="STREAM_TIMEOUT"?new Ce({category:"retryable_stream",code:"STREAM_TIMEOUT",message:`API \u4EE3\u7406\u54CD\u5E94\u8D85\u65F6: ${e}`,retryable:true,context:{rawMessage:e},originalError:t}):e.includes("stream")||e.includes("Stream")||e.includes("SSE")||e.includes("disconnected")||e.includes("incomplete")||e.includes("message_stop")?new Ce({category:"retryable_stream",code:"STREAM_ERROR",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,originalError:t}):dp(e)?new Ce({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,originalError:t}):mv(e)?new Ce({category:"fatal_limit",code:"QUOTA_EXCEEDED",message:e,retryable:false,originalError:t}):new Ce({category:"internal",code:"UNKNOWN",message:e,retryable:false,originalError:t})}function pp(a,e,t){let s=e||"";return s.trim().endsWith("}")?(a==="write_file"||a==="edit_file")&&!s.includes('"content"')?new Ce({category:"tool_truncated",code:"TOOL_MISSING_CONTENT",message:"The content field is missing (likely truncated)",retryable:false,context:{toolName:a,receivedLength:s.length,rawMessage:t.message},originalError:t}):t.message.includes("JSON")||t.message.includes("Unexpected")||t.message.includes("parse")?new Ce({category:"tool_json_invalid",code:"JSON_PARSE_ERROR",message:`Invalid JSON in tool arguments: ${t.message}`,retryable:true,context:{toolName:a,receivedLength:s.length,rawMessage:t.message},originalError:t}):new Ce({category:"tool_json_invalid",code:"TOOL_ERROR",message:t.message,retryable:true,context:{toolName:a},originalError:t}):new Ce({category:"tool_truncated",code:"TOOL_ARGS_TRUNCATED",message:"Tool arguments were truncated during streaming",retryable:false,context:{toolName:a,receivedLength:s.length,rawMessage:t.message},originalError:t})}function Gi(a){switch(a.category){case "retryable_rate_limit":return `API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${a.retryAfter?Math.ceil(a.retryAfter/1e3):3} \u79D2\u540E\u81EA\u52A8\u91CD\u8BD5...`;case "retryable_http":return "The request will be automatically retried.";case "retryable_stream":return "\u7F51\u7EDC\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8FDE...";case "retryable_network":return "\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5...";case "fatal_auth":return "Please check your API key and ensure it has the necessary permissions.";case "fatal_limit":return "You have reached your usage limit. Please check your billing settings or wait for the limit to reset.";case "fatal_context":return "The conversation is too long. Please start a new conversation or use /compact to summarize history.";case "fatal_invalid":return "Please check your request parameters and try again.";case "tool_truncated":return "The tool call was truncated. Please use edit_file with smaller, targeted changes instead of rewriting entire files.";case "tool_json_invalid":return "The tool arguments were invalid. The LLM will retry with corrected parameters.";case "tool_timeout":return "The tool execution timed out. Please try again with a smaller operation.";case "tool_denied":return "The tool call was denied. You can manually approve or adjust permissions.";default:return "An unexpected error occurred. Please try again."}}var Kt={requestMaxRetries:10,streamMaxRetries:5,toolMaxRetries:2,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:3e4,jitterRange:.2,streamIdleTimeoutMs:3e5};function is(a,e){return {...Kt,...a,...e?.requestMaxRetries!==void 0&&{requestMaxRetries:e.requestMaxRetries},...e?.streamMaxRetries!==void 0&&{streamMaxRetries:e.streamMaxRetries},...e?.streamIdleTimeoutMs!==void 0&&{streamIdleTimeoutMs:e.streamIdleTimeoutMs}}}var rs={openai:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5},anthropic:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5},yunwu:{requestMaxRetries:3,streamMaxRetries:10,streamIdleTimeoutMs:9e4},azure:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:6e5},proxy:{requestMaxRetries:10,streamMaxRetries:10,streamIdleTimeoutMs:18e4},gemini:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5}};function dn(a,e){let t=a.toLowerCase();if(t.includes("yunwu"))return rs.yunwu;if(t.includes("azure"))return rs.azure;if(e){let s=e.toLowerCase();if(s.includes("yunwu"))return rs.yunwu;if(s.includes("azure"))return rs.azure;if(!(s.includes("api.anthropic.com")||s.includes("api.openai.com")))return rs.proxy}return t.includes("anthropic")?rs.anthropic:t.includes("gemini")?rs.gemini:rs.openai}var mp=100,gp=200,hp=0;var mr=class extends Error{constructor(e){super(e),this.name="GuardrailTripwireTriggered";}},pn=class extends mr{guardrail_result;constructor(e){let t=`Input guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Safety check failed"}`;super(t),this.name="InputGuardrailTripwireTriggered",this.guardrail_result=e;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info}}},mn=class extends mr{guardrail_result;blocked_output;constructor(e){let t=`Output guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Output safety check failed"}`;super(t),this.name="OutputGuardrailTripwireTriggered",this.guardrail_result=e,this.blocked_output=e.agent_output;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info,blocked_output:this.blocked_output}}},yt=class extends mr{guardrail_result;constructor(e){let t=`Tool guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Tool safety check failed"}`;super(t),this.name="ToolGuardrailTripwireTriggered",this.guardrail_result=e;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info,behavior:this.guardrail_result.output.behavior}}};var Rs=class{static async runInputGuardrails(e,t,s,n){if(e.length===0)return [];let r=e.map(async i=>{let o=Date.now();try{let l=await i.guardrail_function(t,s,n),c={guardrail:i,output:l,execution_time_ms:Date.now()-o};if(l.tripwire_triggered)throw new pn(c);return c}catch(l){if(l instanceof pn)throw l;let c={guardrail:i,output:{tripwire_triggered:true,output_info:{error:l instanceof Error?l.message:String(l),reason:"Guardrail execution failed"}},execution_time_ms:Date.now()-o};throw new pn(c)}});return await Promise.all(r)}static async runOutputGuardrails(e,t,s,n){if(e.length===0)return [];let r=e.map(async i=>{let o=Date.now();try{let l=await i.guardrail_function(t,s,n),c={guardrail:i,agent_output:n,output:l,execution_time_ms:Date.now()-o};if(l.tripwire_triggered)throw new mn(c);return c}catch(l){if(l instanceof mn)throw l;let c={guardrail:i,agent_output:n,output:{tripwire_triggered:true,output_info:{error:l instanceof Error?l.message:String(l),reason:"Guardrail execution failed"}},execution_time_ms:Date.now()-o};throw new mn(c)}});return await Promise.all(r)}static async runToolInputGuardrails(e,t){let s=[];for(let n of e){let r=Date.now();try{let i=await n.guardrail_function(t),o={guardrail:n,output:i,execution_time_ms:Date.now()-r};if(s.push(o),i.behavior.type==="raise_exception")throw new yt(o);if(i.behavior.type==="reject_content")return {results:s,should_execute:!1,rejection_message:i.behavior.message}}catch(i){if(i instanceof yt)throw i;let o={guardrail:n,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-r};throw new yt(o)}}return {results:s,should_execute:true}}static async runToolOutputGuardrails(e,t){let s=[];for(let n of e){let r=Date.now();try{let i=await n.guardrail_function(t),o={guardrail:n,output:i,execution_time_ms:Date.now()-r};if(s.push(o),i.behavior.type==="raise_exception")throw new yt(o);if(i.behavior.type==="reject_content")return {results:s,should_use_output:!1,replacement_message:i.behavior.message}}catch(i){if(i instanceof yt)throw i;let o={guardrail:n,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-r};throw new yt(o)}}return {results:s,should_use_output:true}}};var fp=null,yp=false;function gr(){if(!yp&&(yp=true,typeof process<"u"&&process.env&&!process.env.NEOX_UI_MODE))try{Promise.resolve().then(()=>(W(),qc)).then(a=>{fp=a.cliLogger;}).catch(()=>{});}catch{}return fp}var bp=new WeakMap,yl=null;function vp(){return {writtenFiles:new Map,editedFiles:new Map,editDetails:new Map,fileReadCache:new Map,toolCallHistory:[],createdAt:Date.now()}}function wp(a){if(a){let e=bp.get(a);return e?process.env.CLI_DEBUG==="1"&&gr()?.debug("SESSION",`Retrieved EXISTING SessionState for context: ${Object.keys(a).join(",")}, history: ${e.toolCallHistory.length}`):(e=vp(),bp.set(a,e),process.env.CLI_DEBUG==="1"&&gr()?.debug("SESSION",`Created NEW SessionState for context: ${Object.keys(a).join(",")}`)),e}return yl||(yl=vp()),yl}function bl(a,e,t,s){let n=wp(a);if(process.env.CLI_DEBUG==="1"){let r=gr();r?.debug("SESSION","recordToolCall called:"),r?.debug("SESSION",` - tool: ${e}`),r?.debug("SESSION",` - success: ${s}`),r?.debug("SESSION",` - context exists: ${!!a}`),r?.debug("SESSION",` - context identity: ${a?Object.keys(a).join(","):"none"}`),r?.debug("SESSION",` - history length before: ${n.toolCallHistory.length}`);}n.toolCallHistory.push({name:e,args:t,timestamp:Date.now(),success:s}),process.env.CLI_DEBUG==="1"&&gr()?.debug("SESSION",` - history length after: ${n.toolCallHistory.length}`),n.toolCallHistory.length>100&&n.toolCallHistory.shift();}function Cp(a,e=10){let t=wp(a);if(process.env.CLI_DEBUG==="1"){let s=gr();s?.debug("SESSION","getRecentToolCalls called:"),s?.debug("SESSION",` - context exists: ${!!a}`),s?.debug("SESSION",` - context identity: ${a?Object.keys(a).join(","):"none"}`),s?.debug("SESSION",` - total history length: ${t.toolCallHistory.length}`),s?.debug("SESSION",` - limit: ${e}`),s?.debug("SESSION",` - returning ${Math.min(t.toolCallHistory.length,e)} calls`);}return t.toolCallHistory.slice(-e)}var bv=fileURLToPath(import.meta.url),wl=dirname(bv),Cl=class{logDir;enabled;consoleEnabled;constructor(){this.logDir=this.getLogDirectory(),this.enabled=process.env.MARKOR_TRACING==="1",this.consoleEnabled=process.env.CLI_DEBUG_CONSOLE==="1";try{this.initLogDir(),this.consoleEnabled&&console.log("[Logger] Initialized at:",this.logDir);}catch(e){console.error("[Logger] Failed to initialize:",e.message),this.enabled=false;}}setEnabled(e){this.enabled=e;}getLogDirectory(){if(wl.includes(".asar")||wl.includes("app.asar")){try{if(typeof process<"u"&&process.type==="browser"){let e=process.env.ELECTRON_USER_DATA;if(e)return te__default.join(e,"logs")}}catch{}return te__default.join(In__default.tmpdir(),"neox-logs")}return te__default.join(wl,"../../logs")}initLogDir(){try{Me__default.existsSync(this.logDir)||Me__default.mkdirSync(this.logDir,{recursive:!0});}catch(e){let t=e;t.code==="EACCES"||t.code==="EPERM"?this.enabled=false:(console.warn(`[Logger] Warning: Cannot create log directory: ${t.message}`),this.enabled=false);}}getLogFile(e){let t=new Date().toISOString().split("T")[0];return te__default.join(this.logDir,`${e}-${t}.log`)}write(e,t){if(!this.enabled)return;let s=new Date().toISOString(),n=typeof t=="string"?{message:t}:t||{},r=this.safeStringify({timestamp:s,...n})+`
1056
+ \u26A0\uFE0F IMPORTANT: Now execute the above instructions step by step. Do not ask for confirmation unless the instructions explicitly require it.`:`\u274C Skill execution failed: ${i.error}`}},cp=[Mb,Nb,Bb,Gb,Ub,$b,Fb,jb,zb,Hb,Jb,Kb,Vb,Yb,Zb,ev,tv,Wb,qb,_u,sv,ov,ua,da,pa,Nu,av,Jd,lv];async function un(a,e){e&&Sb(e);let t=e?.capabilities??Ke.capabilities,s=Oe(),n=[...cp];if(a&&n.push($u(a)),s.webSearch?.enabled&&n.push(Ea),s.javaDebug?.enabled)try{let c=await Da(s.javaDebug?.jarPath);n.push(...c),we.info("TOOLS",`Java Debug \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){we.error("TOOLS",`Java Debug \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`),we.error("TOOLS","\u63D0\u793A: \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D JAR \u6587\u4EF6");}if(s.smartRead?.enabled!==false)try{let c=ll(a);n.push(...c),we.info("TOOLS",`readfile \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){we.error("TOOLS",`readfile \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`);}let r=typeof process<"u"&&process.type==="renderer";t?.terminal&&r&&n.push(...ni()),t?.editor&&r&&n.push(...ri());let i=Tb(n,t),o=s.enabledTools||{},l=i.filter(c=>o[c.name]!==false);return Yd(l)}function ji(a){return {output_info:a,behavior:{type:"allow"}}}function up(a,e){return {output_info:e,behavior:{type:"reject_content",message:a}}}function cv(a){let e=a.match(/Error\s+(?:code\s+)?(\d{3})/i);if(e)return e[1];let t=a.match(/(\d{3}):\s*([^<\n]+)/);return t?t[1]:null}function uv(a){let e=a.match(/<title>[^|]*\|\s*\d{3}:\s*([^<]+)<\/title>/i);if(e)return e[1].trim();let t=a.match(/<h1[^>]*>(?:<[^>]+>)*([^<]+?(?:\s+\d{3})?)<\/(?:[^>]+>)*<\/h1>/i);if(t)return t[1].replace(/Error code\s+\d{3}/i,"").trim();let s=a.match(/Error\s+code\s+(\d{3})/i);if(s){let r=s[1];return {502:"Bad gateway",503:"Service unavailable",504:"Gateway timeout",520:"Unknown error",521:"Web server is down",522:"Connection timed out",523:"Origin is unreachable",524:"A timeout occurred"}[r]||"Server error"}let n=a.match(/<span[^>]*class="inline-block"[^>]*>([^<]+)<\/span>/i);return n?n[1].trim():null}function dv(a){let e=a.match(/truncate[^>]*>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})<\/span>/);if(e)return e[1];let t=a.match(/<title>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:null}function pr(a){return a.trim().startsWith("<!DOCTYPE html")||a.trim().startsWith("<html")||/<html[^>]*>/i.test(a)}function pv(a){let e=a.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function _s(a,e){let t=pv(a);if(t)try{let i=JSON.parse(t);if(i.error){let o=i.error,l=o.type||o.code||(e?`HTTP_${e}`:"API_ERROR"),c=o.message||"API error",u;if(o.type==="usage_limit_reached"){let d=o.resets_at?new Date(o.resets_at*1e3).toLocaleString():void 0,p=o.resets_in_seconds;if(p){let h=Math.floor(p/3600),g=Math.floor(p%3600/60);u=`Usage limit reached (${o.plan_type||"unknown"} plan). Resets in ${h}h ${g}m.`;}else d&&(u=`Usage limit reached (${o.plan_type||"unknown"} plan). Resets at ${d}.`);}return {code:l,message:c,detail:u}}}catch{}if(a.trim().startsWith("{"))try{let i=JSON.parse(a);if(i.error){let o=i.error;return {code:o.type||o.code||(e?`HTTP_${e}`:"API_ERROR"),message:o.message||"API error"}}}catch{}if(pr(a)){let i=cv(a)||String(e||"UNKNOWN"),o=uv(a)||"Server error",l=dv(a),c;return l&&(l.includes("cloudflare")?c=`The server (${l}) is protected by Cloudflare but is not responding.`:c=`The API server (${l}) is not responding. This may be a temporary issue with your API provider.`),{code:`HTTP_${i}`,message:o,detail:c}}let s=a.match(/OpenAI.*error:\s*(\d+)\s*-\s*(.*)/i);if(s){let i=s[1],o=s[2];if(pr(o)){let l=_s(o,parseInt(i,10));return {code:l.code,message:l.message,detail:l.detail}}return o=o.trim(),o.length>200&&(o=o.slice(0,200)+"..."),{code:`HTTP_${i}`,message:o}}let n=a.match(/Anthropic.*error:\s*(\d+)\s*-\s*(.*)/i);if(n){let i=n[1],o=n[2].trim();return o.length>200&&(o=o.slice(0,200)+"..."),{code:`HTTP_${i}`,message:o}}if(a.includes("ECONNREFUSED"))return {code:"NETWORK_ERROR",message:"Connection refused",detail:"Unable to connect to the API server. Please check your network connection."};if(a.includes("ETIMEDOUT")||a.includes("timeout"))return {code:"TIMEOUT",message:"Connection timeout",detail:"The request took too long to complete. Please try again."};if(a.includes("ENOTFOUND"))return {code:"DNS_ERROR",message:"Server not found",detail:"Could not resolve the API server address. Please check your API base URL."};if(/context.*window.*exceeded/i.test(a)||/maximum.*context.*length/i.test(a))return {code:"CONTEXT_EXCEEDED",message:"Context window exceeded",detail:"The conversation is too long. Please start a new session or use /compact."};if(/rate.*limit/i.test(a)||a.includes("429"))return {code:"RATE_LIMIT",message:"Rate limit exceeded",detail:"Too many requests. Please wait a moment before trying again."};if(a.includes("401")||/unauthorized/i.test(a))return {code:"AUTH_ERROR",message:"Authentication failed",detail:"Please check your API key in settings."};if(a.includes("403")||/forbidden/i.test(a))return {code:"FORBIDDEN",message:"Access denied",detail:"Your API key does not have permission for this operation."};let r=a;return r=r.replace(/^Error:\s*/i,""),r=r.replace(/^Request failed with status code\s+\d+:\s*/i,""),r.length>300&&(r=r.slice(0,300)+"..."),{code:e?`HTTP_${e}`:"UNKNOWN",message:r}}var Ce=class a extends Error{category;code;retryable;retryAfter;context;originalError;constructor(e){super(e.message),this.name="NeoxError",this.category=e.category,this.code=e.code,this.retryable=e.retryable,this.retryAfter=e.retryAfter,this.context=e.context,this.originalError=e.originalError,Error.captureStackTrace&&Error.captureStackTrace(this,a);}withContext(e){return new a({...this,context:{...this.context,...e}})}toJSON(){return {name:this.name,category:this.category,code:this.code,message:this.message,retryable:this.retryable,retryAfter:this.retryAfter,context:this.context,stack:this.stack}}};function Jt(a){if(!a)return;if(typeof a!="string")return typeof a=="number"&&a>0?Math.ceil(a*1e3):void 0;let e=a.trim(),t=e.match(/^(\d+(?:\.\d+)?)\s*ms$/i);if(t){let r=parseFloat(t[1]);return r>0?Math.ceil(r):void 0}let s=parseFloat(e);if(!isNaN(s)&&s>0)return Math.ceil(s*1e3);let n=new Date(e);if(!isNaN(n.getTime())){let r=n.getTime()-Date.now();return r>0?Math.ceil(r):void 0}}function mv(a){switch(a){case 502:return 3e3;case 503:return 5e3;case 504:return 2e3;default:return 2e3}}function Bi(a){if(!a)return;let e=a["retry-after"]||a["Retry-After"];if(e){let r=Jt(e);if(r)return r}let t=a["retry-after-ms"]||a["Retry-After-Ms"];if(t){let r=parseFloat(t);if(!isNaN(r)&&r>0)return Math.ceil(r)}let s=a["x-ratelimit-reset-requests"];if(s){let r=Jt(s);if(r)return r}let n=a["anthropic-ratelimit-requests-reset"];if(n){let r=new Date(n);if(!isNaN(r.getTime())){let i=r.getTime()-Date.now();return i>0?Math.ceil(i):void 0}}}function fl(a){return typeof a=="object"&&a!==null&&"message"in a&&typeof a.message=="string"}function dp(a){return [/context.*window.*exceeded/i,/context.*length.*exceeded/i,/maximum.*context.*length/i,/token.*limit.*exceeded/i,/input.*too.*long/i].some(t=>t.test(a))}function gv(a){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(a))}function hv(a){if(a){if(typeof a=="string")return a;if(typeof a=="object"){if(typeof a.error=="string")return a.error;if(a.error?.message)return a.error.message;if(a.message)return a.message}}}function ft(a){if(a instanceof Ce)return a;let e=a instanceof Error?a.message:String(a),t=a instanceof Error?a:void 0,s=fl(a)?a:void 0,r=(s?hv(s.response?.data):void 0)||e;if(s?.response?.status){let i=s.response.status,o=Bi(s.response.headers),l=s.response.headers?.["x-request-id"]||s.response.headers?.["cf-ray"];if(i===429){let c=s.response.data,u=c?.error?.type;return u==="usage_limit_reached"||u==="usage_not_included"?new Ce({category:"fatal_limit",code:"USAGE_LIMIT_REACHED",message:c?.error?.message||"Usage limit reached",retryable:false,context:{httpStatus:i,requestId:l},originalError:t}):new Ce({category:"retryable_http",code:`HTTP_${i}`,message:r,retryable:true,retryAfter:o,context:{httpStatus:i,requestId:l},originalError:t})}if(i===502||i===503||i===504){let c=r;if(pr(r)){let d=_s(r,i);c=d.message,d.detail&&(c+=`
1057
+ `+d.detail);}let u=o||mv(i);return new Ce({category:"retryable_rate_limit",code:`PROXY_${i}`,message:c||`API \u4EE3\u7406\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528 (${i})`,retryable:true,retryAfter:u,context:{httpStatus:i,requestId:l,rawMessage:r},originalError:t})}if(i>=500){let c=r;if(pr(r)){let u=_s(r,i);c=u.message,u.detail&&(c+=`
1058
+ `+u.detail);}return new Ce({category:"retryable_http",code:`HTTP_${i}`,message:c,retryable:true,retryAfter:o,context:{httpStatus:i,requestId:l,rawMessage:r},originalError:t})}if(i===401)return new Ce({category:"fatal_auth",code:"UNAUTHORIZED",message:r||"Authentication failed. Please check your API key.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===403)return new Ce({category:"fatal_auth",code:"FORBIDDEN",message:r||"Access denied. Please check your API permissions.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===400)return dp(e)?new Ce({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t}):r.includes("Upstream request failed")||r.includes("upstream")||r.includes("gateway")?new Ce({category:"retryable_http",code:"PROXY_UPSTREAM_FAILED",message:r||"Proxy upstream request failed",retryable:true,context:{httpStatus:i,requestId:l},originalError:t}):new Ce({category:"fatal_invalid",code:"INVALID_REQUEST",message:r,retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i>=400&&i<500)return new Ce({category:"fatal_invalid",code:`HTTP_${i}`,message:r,retryable:false,context:{httpStatus:i,requestId:l},originalError:t})}if(fl(a)){let i=a.code,o=a.name;if(i==="ERR_CANCELED"||o==="CanceledError"||o==="AbortError")return new Ce({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:t});if(i==="ECONNREFUSED"||i==="ENOTFOUND"||i==="ECONNRESET")return new Ce({category:"retryable_network",code:i,message:`Network error: ${e}`,retryable:true,originalError:t});if(i==="ETIMEDOUT"||i==="ESOCKETTIMEDOUT")return new Ce({category:"retryable_network",code:"TIMEOUT",message:`Connection timeout: ${e}`,retryable:true,originalError:t})}return a instanceof Error&&a.name==="AbortError"?new Ce({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:a}):fl(a)&&a.code==="STREAM_INCOMPLETE"?new Ce({category:"retryable_stream",code:"STREAM_INCOMPLETE",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,context:{toolName:a.toolName,rawMessage:e},originalError:t}):a?.code==="STREAM_TIMEOUT"?new Ce({category:"retryable_stream",code:"STREAM_TIMEOUT",message:`API \u4EE3\u7406\u54CD\u5E94\u8D85\u65F6: ${e}`,retryable:true,context:{rawMessage:e},originalError:t}):e.includes("stream")||e.includes("Stream")||e.includes("SSE")||e.includes("disconnected")||e.includes("incomplete")||e.includes("message_stop")?new Ce({category:"retryable_stream",code:"STREAM_ERROR",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,originalError:t}):dp(e)?new Ce({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,originalError:t}):gv(e)?new Ce({category:"fatal_limit",code:"QUOTA_EXCEEDED",message:e,retryable:false,originalError:t}):new Ce({category:"internal",code:"UNKNOWN",message:e,retryable:false,originalError:t})}function pp(a,e,t){let s=e||"";return s.trim().endsWith("}")?(a==="write_file"||a==="edit_file")&&!s.includes('"content"')?new Ce({category:"tool_truncated",code:"TOOL_MISSING_CONTENT",message:"The content field is missing (likely truncated)",retryable:false,context:{toolName:a,receivedLength:s.length,rawMessage:t.message},originalError:t}):t.message.includes("JSON")||t.message.includes("Unexpected")||t.message.includes("parse")?new Ce({category:"tool_json_invalid",code:"JSON_PARSE_ERROR",message:`Invalid JSON in tool arguments: ${t.message}`,retryable:true,context:{toolName:a,receivedLength:s.length,rawMessage:t.message},originalError:t}):new Ce({category:"tool_json_invalid",code:"TOOL_ERROR",message:t.message,retryable:true,context:{toolName:a},originalError:t}):new Ce({category:"tool_truncated",code:"TOOL_ARGS_TRUNCATED",message:"Tool arguments were truncated during streaming",retryable:false,context:{toolName:a,receivedLength:s.length,rawMessage:t.message},originalError:t})}function Gi(a){switch(a.category){case "retryable_rate_limit":return `API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${a.retryAfter?Math.ceil(a.retryAfter/1e3):3} \u79D2\u540E\u81EA\u52A8\u91CD\u8BD5...`;case "retryable_http":return "The request will be automatically retried.";case "retryable_stream":return "\u7F51\u7EDC\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8FDE...";case "retryable_network":return "\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5...";case "fatal_auth":return "Please check your API key and ensure it has the necessary permissions.";case "fatal_limit":return "You have reached your usage limit. Please check your billing settings or wait for the limit to reset.";case "fatal_context":return "The conversation is too long. Please start a new conversation or use /compact to summarize history.";case "fatal_invalid":return "Please check your request parameters and try again.";case "tool_truncated":return "The tool call was truncated. Please use edit_file with smaller, targeted changes instead of rewriting entire files.";case "tool_json_invalid":return "The tool arguments were invalid. The LLM will retry with corrected parameters.";case "tool_timeout":return "The tool execution timed out. Please try again with a smaller operation.";case "tool_denied":return "The tool call was denied. You can manually approve or adjust permissions.";default:return "An unexpected error occurred. Please try again."}}var Kt={requestMaxRetries:10,streamMaxRetries:5,toolMaxRetries:2,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:3e4,jitterRange:.2,streamIdleTimeoutMs:3e5};function is(a,e){return {...Kt,...a,...e?.requestMaxRetries!==void 0&&{requestMaxRetries:e.requestMaxRetries},...e?.streamMaxRetries!==void 0&&{streamMaxRetries:e.streamMaxRetries},...e?.streamIdleTimeoutMs!==void 0&&{streamIdleTimeoutMs:e.streamIdleTimeoutMs}}}var rs={openai:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5},anthropic:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5},yunwu:{requestMaxRetries:3,streamMaxRetries:10,streamIdleTimeoutMs:9e4},azure:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:6e5},proxy:{requestMaxRetries:10,streamMaxRetries:10,streamIdleTimeoutMs:18e4},gemini:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5}};function dn(a,e){let t=a.toLowerCase();if(t.includes("yunwu"))return rs.yunwu;if(t.includes("azure"))return rs.azure;if(e){let s=e.toLowerCase();if(s.includes("yunwu"))return rs.yunwu;if(s.includes("azure"))return rs.azure;if(!(s.includes("api.anthropic.com")||s.includes("api.openai.com")))return rs.proxy}return t.includes("anthropic")?rs.anthropic:t.includes("gemini")?rs.gemini:rs.openai}var mp=100,gp=200,hp=0;var mr=class extends Error{constructor(e){super(e),this.name="GuardrailTripwireTriggered";}},pn=class extends mr{guardrail_result;constructor(e){let t=`Input guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Safety check failed"}`;super(t),this.name="InputGuardrailTripwireTriggered",this.guardrail_result=e;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info}}},mn=class extends mr{guardrail_result;blocked_output;constructor(e){let t=`Output guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Output safety check failed"}`;super(t),this.name="OutputGuardrailTripwireTriggered",this.guardrail_result=e,this.blocked_output=e.agent_output;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info,blocked_output:this.blocked_output}}},yt=class extends mr{guardrail_result;constructor(e){let t=`Tool guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Tool safety check failed"}`;super(t),this.name="ToolGuardrailTripwireTriggered",this.guardrail_result=e;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info,behavior:this.guardrail_result.output.behavior}}};var Rs=class{static async runInputGuardrails(e,t,s,n){if(e.length===0)return [];let r=e.map(async i=>{let o=Date.now();try{let l=await i.guardrail_function(t,s,n),c={guardrail:i,output:l,execution_time_ms:Date.now()-o};if(l.tripwire_triggered)throw new pn(c);return c}catch(l){if(l instanceof pn)throw l;let c={guardrail:i,output:{tripwire_triggered:true,output_info:{error:l instanceof Error?l.message:String(l),reason:"Guardrail execution failed"}},execution_time_ms:Date.now()-o};throw new pn(c)}});return await Promise.all(r)}static async runOutputGuardrails(e,t,s,n){if(e.length===0)return [];let r=e.map(async i=>{let o=Date.now();try{let l=await i.guardrail_function(t,s,n),c={guardrail:i,agent_output:n,output:l,execution_time_ms:Date.now()-o};if(l.tripwire_triggered)throw new mn(c);return c}catch(l){if(l instanceof mn)throw l;let c={guardrail:i,agent_output:n,output:{tripwire_triggered:true,output_info:{error:l instanceof Error?l.message:String(l),reason:"Guardrail execution failed"}},execution_time_ms:Date.now()-o};throw new mn(c)}});return await Promise.all(r)}static async runToolInputGuardrails(e,t){let s=[];for(let n of e){let r=Date.now();try{let i=await n.guardrail_function(t),o={guardrail:n,output:i,execution_time_ms:Date.now()-r};if(s.push(o),i.behavior.type==="raise_exception")throw new yt(o);if(i.behavior.type==="reject_content")return {results:s,should_execute:!1,rejection_message:i.behavior.message}}catch(i){if(i instanceof yt)throw i;let o={guardrail:n,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-r};throw new yt(o)}}return {results:s,should_execute:true}}static async runToolOutputGuardrails(e,t){let s=[];for(let n of e){let r=Date.now();try{let i=await n.guardrail_function(t),o={guardrail:n,output:i,execution_time_ms:Date.now()-r};if(s.push(o),i.behavior.type==="raise_exception")throw new yt(o);if(i.behavior.type==="reject_content")return {results:s,should_use_output:!1,replacement_message:i.behavior.message}}catch(i){if(i instanceof yt)throw i;let o={guardrail:n,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-r};throw new yt(o)}}return {results:s,should_use_output:true}}};var fp=null,yp=false;function gr(){if(!yp&&(yp=true,typeof process<"u"&&process.env&&!process.env.NEOX_UI_MODE))try{Promise.resolve().then(()=>(W(),qc)).then(a=>{fp=a.cliLogger;}).catch(()=>{});}catch{}return fp}var bp=new WeakMap,yl=null;function vp(){return {writtenFiles:new Map,editedFiles:new Map,editDetails:new Map,fileReadCache:new Map,toolCallHistory:[],createdAt:Date.now()}}function wp(a){if(a){let e=bp.get(a);return e?process.env.CLI_DEBUG==="1"&&gr()?.debug("SESSION",`Retrieved EXISTING SessionState for context: ${Object.keys(a).join(",")}, history: ${e.toolCallHistory.length}`):(e=vp(),bp.set(a,e),process.env.CLI_DEBUG==="1"&&gr()?.debug("SESSION",`Created NEW SessionState for context: ${Object.keys(a).join(",")}`)),e}return yl||(yl=vp()),yl}function bl(a,e,t,s){let n=wp(a);if(process.env.CLI_DEBUG==="1"){let r=gr();r?.debug("SESSION","recordToolCall called:"),r?.debug("SESSION",` - tool: ${e}`),r?.debug("SESSION",` - success: ${s}`),r?.debug("SESSION",` - context exists: ${!!a}`),r?.debug("SESSION",` - context identity: ${a?Object.keys(a).join(","):"none"}`),r?.debug("SESSION",` - history length before: ${n.toolCallHistory.length}`);}n.toolCallHistory.push({name:e,args:t,timestamp:Date.now(),success:s}),process.env.CLI_DEBUG==="1"&&gr()?.debug("SESSION",` - history length after: ${n.toolCallHistory.length}`),n.toolCallHistory.length>100&&n.toolCallHistory.shift();}function Cp(a,e=10){let t=wp(a);if(process.env.CLI_DEBUG==="1"){let s=gr();s?.debug("SESSION","getRecentToolCalls called:"),s?.debug("SESSION",` - context exists: ${!!a}`),s?.debug("SESSION",` - context identity: ${a?Object.keys(a).join(","):"none"}`),s?.debug("SESSION",` - total history length: ${t.toolCallHistory.length}`),s?.debug("SESSION",` - limit: ${e}`),s?.debug("SESSION",` - returning ${Math.min(t.toolCallHistory.length,e)} calls`);}return t.toolCallHistory.slice(-e)}var vv=fileURLToPath(import.meta.url),wl=dirname(vv),Cl=class{logDir;enabled;consoleEnabled;constructor(){this.logDir=this.getLogDirectory(),this.enabled=process.env.MARKOR_TRACING==="1",this.consoleEnabled=process.env.CLI_DEBUG_CONSOLE==="1";try{this.initLogDir(),this.consoleEnabled&&console.log("[Logger] Initialized at:",this.logDir);}catch(e){console.error("[Logger] Failed to initialize:",e.message),this.enabled=false;}}setEnabled(e){this.enabled=e;}getLogDirectory(){if(wl.includes(".asar")||wl.includes("app.asar")){try{if(typeof process<"u"&&process.type==="browser"){let e=process.env.ELECTRON_USER_DATA;if(e)return te__default.join(e,"logs")}}catch{}return te__default.join(In__default.tmpdir(),"neox-logs")}return te__default.join(wl,"../../logs")}initLogDir(){try{Me__default.existsSync(this.logDir)||Me__default.mkdirSync(this.logDir,{recursive:!0});}catch(e){let t=e;t.code==="EACCES"||t.code==="EPERM"?this.enabled=false:(console.warn(`[Logger] Warning: Cannot create log directory: ${t.message}`),this.enabled=false);}}getLogFile(e){let t=new Date().toISOString().split("T")[0];return te__default.join(this.logDir,`${e}-${t}.log`)}write(e,t){if(!this.enabled)return;let s=new Date().toISOString(),n=typeof t=="string"?{message:t}:t||{},r=this.safeStringify({timestamp:s,...n})+`
1059
1059
  `;if(this.enabled)try{let i=this.getLogFile(e);Me__default.appendFileSync(i,r,"utf-8");}catch(i){(i.code==="EACCES"||i.code==="EPERM")&&(this.enabled=false);}}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(s,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return s==="parser"||s==="socket"||s==="_httpMessage"||s==="req"||s==="res"?"[Omitted]":n&&n.type==="Buffer"&&Array.isArray(n.data)?"[Buffer]":typeof n=="function"?"[Function]":n})}llmRequest(e,t,s,n,r){let i=s.tools?.map(o=>({name:o.name,description:o.description,parameters:o.parameters}));this.write("llm",{type:"REQUEST",provider:e,model:t,url:n,headers:r,messagesCount:s.messages?.length||0,messages:s.messages,toolsCount:s.tools?.length||0,tools:i,temperature:s.temperature});}llmResponse(e,t,s,n){this.write("llm",{type:"RESPONSE",provider:e,duration:`${t}ms`,usage:s,finishReason:n.finish_reason,content:n.content,contentLength:n.content?.length||0,toolCallsCount:n.tool_calls?.length||0,toolCalls:n.tool_calls});}llmError(e,t){let s={type:"ERROR",provider:e,error:t.message,status:t.response?.status};if(t.response?.data)try{let n=t.response.data;typeof n=="string"?s.data=n:typeof n=="object"&&(s.data={error:n.error,message:n.message,type:n.type,code:n.code});}catch{s.data="[Could not serialize response data]";}this.write("llm",s);}agentStart(e){this.write("agent",{type:"START",task:e});}agentIteration(e,t){this.write("agent",{type:"ITERATION",iteration:e,action:t});}agentComplete(e,t,s){this.write("agent",{type:"COMPLETE",iterations:e,toolCalls:t,usage:s});}agentError(e){this.write("agent",{type:"ERROR",error:e});}toolCall(e,t){this.write("tool",{type:"CALL",tool:e,args:t});}toolResult(e,t,s,n){this.write("tool",{type:"RESULT",tool:e,success:t,resultLength:s,duration:`${n}ms`});}toolError(e,t){this.write("tool",{type:"ERROR",tool:e,error:t});}},ge=new Cl;function kp(a,e){let t=a||"Unknown error",s=t.toLowerCase(),n=e?.providerName?.trim()||"LLM";if(s.includes("timeout")){let r=Math.round((e?.timeoutMs??12e4)/1e3);return [`\u23F1\uFE0F ${n} \u8BF7\u6C42\u8D85\u65F6 (${r}s)\u3002${n} \u63A5\u53E3\u5F53\u524D\u53EF\u80FD\u4E0D\u7A33\u5B9A\uFF0C\u53EF\u4EE5\u7A0D\u540E\u91CD\u8BD5\u6216\u5207\u6362\u5176\u4ED6\u6A21\u578B\u3002`,"\u5982\u679C\u591A\u6B21\u8D85\u65F6\u8BF7\u544A\u8BC9\u6211\u4EEC\uFF0C\u65B9\u4FBF\u6392\u67E5\u3002",`\u539F\u59CB\u9519\u8BEF\uFF1A${t}`].join(`
1060
- `)}return t}var wv=new vv({allErrors:true,strict:false});function Cv(a){let e=(a||"").trim();if(e.startsWith("```")){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t&&t[1])return t[1].trim()}return e}function kv(a){return !a||a.length===0?[]:a.map(e=>{let t=e.instancePath||e.schemaPath||"";return e.keyword==="additionalProperties"&&typeof e.params?.additionalProperty=="string"?`${t} should not contain property "${e.params.additionalProperty}"`:`${t} ${e.message||""}`.trim()})}var Wi=class{constructor(e){this.definition=e;this.validateFn=wv.compile(e.schema);}validateFn;get responseFormatPayload(){return {type:"json_schema",json_schema:{name:this.definition.name,schema:this.definition.schema,strict:this.definition.strict??true}}}buildSystemPrompt(){let e=JSON.stringify(this.definition.schema,null,2);return [`You must respond with valid JSON that exactly matches the schema "${this.definition.name}".`,"Do not include explanations, markdown code fences, or additional commentary.","Schema:",e].join(`
1060
+ `)}return t}var Cv=new wv({allErrors:true,strict:false});function kv(a){let e=(a||"").trim();if(e.startsWith("```")){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t&&t[1])return t[1].trim()}return e}function Sv(a){return !a||a.length===0?[]:a.map(e=>{let t=e.instancePath||e.schemaPath||"";return e.keyword==="additionalProperties"&&typeof e.params?.additionalProperty=="string"?`${t} should not contain property "${e.params.additionalProperty}"`:`${t} ${e.message||""}`.trim()})}var Wi=class{constructor(e){this.definition=e;this.validateFn=Cv.compile(e.schema);}validateFn;get responseFormatPayload(){return {type:"json_schema",json_schema:{name:this.definition.name,schema:this.definition.schema,strict:this.definition.strict??true}}}buildSystemPrompt(){let e=JSON.stringify(this.definition.schema,null,2);return [`You must respond with valid JSON that exactly matches the schema "${this.definition.name}".`,"Do not include explanations, markdown code fences, or additional commentary.","Schema:",e].join(`
1061
1061
 
1062
- `)}validate(e){let t=Cv(e||"");if(!t)return {ok:false,reason:"empty_output",message:"The model returned an empty response."};let s;try{s=JSON.parse(t);}catch(r){return {ok:false,reason:"parse_error",message:r?.message||"Failed to parse JSON output."}}return this.validateFn(s)?{ok:true,parsed:s,normalized:JSON.stringify(s,null,2)}:{ok:false,reason:"schema_mismatch",message:"Response does not match the required JSON schema.",errors:kv(this.validateFn.errors)}}buildRetryPrompt(e){let t=[`Your previous response did not satisfy the required JSON schema "${this.definition.name}".`];return e.errors&&e.errors.length>0?t.push(`Validation issues:
1062
+ `)}validate(e){let t=kv(e||"");if(!t)return {ok:false,reason:"empty_output",message:"The model returned an empty response."};let s;try{s=JSON.parse(t);}catch(r){return {ok:false,reason:"parse_error",message:r?.message||"Failed to parse JSON output."}}return this.validateFn(s)?{ok:true,parsed:s,normalized:JSON.stringify(s,null,2)}:{ok:false,reason:"schema_mismatch",message:"Response does not match the required JSON schema.",errors:Sv(this.validateFn.errors)}}buildRetryPrompt(e){let t=[`Your previous response did not satisfy the required JSON schema "${this.definition.name}".`];return e.errors&&e.errors.length>0?t.push(`Validation issues:
1063
1063
  - `+e.errors.join(`
1064
1064
  - `)):e.message&&t.push(`Validation issue: ${e.message}`),t.push("Return ONLY valid minified JSON (no code fences, no commentary) that matches the schema below:",JSON.stringify(this.definition.schema,null,2)),t.join(`
1065
1065
 
1066
- `)}};function Sl(a,e={}){let{initialDelayMs:t=Kt.initialDelayMs,backoffFactor:s=Kt.backoffFactor,maxDelayMs:n=Kt.maxDelayMs,jitterRange:r=Kt.jitterRange}=e,i=Math.max(0,a-1),o=t*Math.pow(s,i),l=1+(Math.random()*2-1)*r,c=o*l,u=Math.min(c,n);return Math.floor(u)}function os(a,e,t){return a!==void 0&&a>0?a:Sl(e,t)}function gn(a){return new Promise(e=>setTimeout(e,a))}function As(a,e){return new Promise((t,s)=>{if(e?.aborted){s(new DOMException("Aborted","AbortError"));return}let n=setTimeout(t,a),r=()=>{clearTimeout(n),s(new DOMException("Aborted","AbortError"));};e?.addEventListener("abort",r,{once:true});let i=()=>{e?.removeEventListener("abort",r);};setTimeout(()=>{i(),t();},a);})}function nt(a){if(a<1e3)return `${a}ms`;let e=a/1e3;return e<60?`${e.toFixed(1)}s`:`${(e/60).toFixed(1)}m`}var Sv={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},xv={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function Tv(a,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return Sl(a,Sv)}function hr(a,e,t){return a==="retryable_rate_limit"?Tv(e,t):a==="retryable_stream"||a==="retryable_network"?Sl(e,xv):os(t,e)}W();W();var _v=2e3,Sp={Read:"file_read",Write:"file_write",Edit:"file_edit",Glob:"file_search",Grep:"file_search",NotebookEdit:"file_edit",Bash:"bash",BashOutput:"bash",WebFetch:"web_fetch",WebSearch:"web_search",Task:"task"},Rv={file_read:{system:`\u4F60\u662F\u4E00\u4E2A\u4EE3\u7801\u5206\u6790\u52A9\u624B\u3002\u8BF7\u5C06\u6587\u4EF6\u5185\u5BB9\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1066
+ `)}};function Sl(a,e={}){let{initialDelayMs:t=Kt.initialDelayMs,backoffFactor:s=Kt.backoffFactor,maxDelayMs:n=Kt.maxDelayMs,jitterRange:r=Kt.jitterRange}=e,i=Math.max(0,a-1),o=t*Math.pow(s,i),l=1+(Math.random()*2-1)*r,c=o*l,u=Math.min(c,n);return Math.floor(u)}function os(a,e,t){return a!==void 0&&a>0?a:Sl(e,t)}function gn(a){return new Promise(e=>setTimeout(e,a))}function As(a,e){return new Promise((t,s)=>{if(e?.aborted){s(new DOMException("Aborted","AbortError"));return}let n=setTimeout(t,a),r=()=>{clearTimeout(n),s(new DOMException("Aborted","AbortError"));};e?.addEventListener("abort",r,{once:true});let i=()=>{e?.removeEventListener("abort",r);};setTimeout(()=>{i(),t();},a);})}function nt(a){if(a<1e3)return `${a}ms`;let e=a/1e3;return e<60?`${e.toFixed(1)}s`:`${(e/60).toFixed(1)}m`}var xv={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},Tv={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function _v(a,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return Sl(a,xv)}function hr(a,e,t){return a==="retryable_rate_limit"?_v(e,t):a==="retryable_stream"||a==="retryable_network"?Sl(e,Tv):os(t,e)}W();W();var Rv=2e3,Sp={Read:"file_read",Write:"file_write",Edit:"file_edit",Glob:"file_search",Grep:"file_search",NotebookEdit:"file_edit",Bash:"bash",BashOutput:"bash",WebFetch:"web_fetch",WebSearch:"web_search",Task:"task"},Av={file_read:{system:`\u4F60\u662F\u4E00\u4E2A\u4EE3\u7801\u5206\u6790\u52A9\u624B\u3002\u8BF7\u5C06\u6587\u4EF6\u5185\u5BB9\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1067
1067
  1. \u6587\u4EF6\u7C7B\u578B\u548C\u4E3B\u8981\u529F\u80FD
1068
1068
  2. \u5173\u952E\u7684\u51FD\u6570/\u7C7B/\u63A5\u53E3\u5B9A\u4E49\uFF08\u53EA\u4FDD\u7559\u7B7E\u540D\uFF09
1069
1069
  3. \u91CD\u8981\u7684\u914D\u7F6E\u9879\u6216\u5E38\u91CF
@@ -1128,9 +1128,9 @@ ${a}
1128
1128
  \u683C\u5F0F\uFF1A[\u4EFB\u52A1\u7C7B\u578B] \u7ED3\u8BBA: \u6458\u8981`,user:a=>`\u4EFB\u52A1\u7ED3\u679C:
1129
1129
  ${a}
1130
1130
 
1131
- \u8BF7\u538B\u7F29\u8FD9\u4E2A\u4EFB\u52A1\u7ED3\u679C\u3002`}},as=class{supportedTools=Object.keys(Sp);debug;llmProvider;model;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.llmProvider=e?.llmProvider,this.model=e?.model;}getToolType(e){return e.startsWith("mcp__")?"mcp":Sp[e]||"other"}needsLLMCompression(e,t,s){let n=this.getToolType(e);if(["web_fetch","web_search","task"].includes(n))return true;let i=128e3,o=2e5,l=s||i,c=Math.max(.3,Math.min(2,l/o)),d={file_read:2e4,file_write:8e3,file_edit:5e3,file_search:1e4,bash:15e3,web_fetch:0,web_search:0,image_analysis:3e3,mcp:1e4,task:0,other:15e3}[n]??15e3,p=Math.floor(d*c);return this.debug&&m.debug("ToolCompressor",`[${e}] contextWindow=${l}${s?"":"(default)"}, scaleFactor=${c.toFixed(2)}, threshold=${p}`),t.length>p}async compress(e,t,s){let n=this.getToolType(e),r=t.length,i=this.extractMetadata(n,t,e),o=this.needsLLMCompression(e,t,s.contextWindow),l=s.llmProvider||this.llmProvider,c,u=false;if(o&&l&&s.enableLLMCompression!==false){let d=await this.compressWithLLM(n,t,l,s.model||this.model,i);d?(c=d,u=true):c=this.compressWithRules(n,t,i);}else c=this.compressWithRules(n,t,i);if(this.debug){let d=((1-c.length/r)*100).toFixed(1);m.debug("ToolCompressor",`[${e}] ${r} \u2192 ${c.length} chars (${d}% saved, LLM: ${u})`);}return {content:c,originalLength:r,compressedLength:c.length,strategy:n,usedLLM:u,metadata:i}}extractMetadata(e,t,s){let n={};switch(e){case "file_read":case "file_write":case "file_edit":let r=t.match(/(?:file|path)[:\s]+([^\n]+)/i);r&&(n.filePath=r[1].trim());break;case "bash":let i=t.match(/(?:command|cmd)[:\s]+([^\n]+)/i);i&&(n.command=i[1].trim()),/error|failed|exit code [1-9]/i.test(t)&&(n.exitCode=1);break;case "web_fetch":case "web_search":let o=t.match(/https?:\/\/[^\s\)]+/g);o&&(n.urls=[...new Set(o)].slice(0,10));break}return n}async compressWithLLM(e,t,s,n,r){let i=Rv[e];if(!i)return null;try{let l=t.length>8e3?t.slice(0,8e3)+`
1131
+ \u8BF7\u538B\u7F29\u8FD9\u4E2A\u4EFB\u52A1\u7ED3\u679C\u3002`}},as=class{supportedTools=Object.keys(Sp);debug;llmProvider;model;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.llmProvider=e?.llmProvider,this.model=e?.model;}getToolType(e){return e.startsWith("mcp__")?"mcp":Sp[e]||"other"}needsLLMCompression(e,t,s){let n=this.getToolType(e);if(["web_fetch","web_search","task"].includes(n))return true;let i=128e3,o=2e5,l=s||i,c=Math.max(.3,Math.min(2,l/o)),d={file_read:2e4,file_write:8e3,file_edit:5e3,file_search:1e4,bash:15e3,web_fetch:0,web_search:0,image_analysis:3e3,mcp:1e4,task:0,other:15e3}[n]??15e3,p=Math.floor(d*c);return this.debug&&m.debug("ToolCompressor",`[${e}] contextWindow=${l}${s?"":"(default)"}, scaleFactor=${c.toFixed(2)}, threshold=${p}`),t.length>p}async compress(e,t,s){let n=this.getToolType(e),r=t.length,i=this.extractMetadata(n,t,e),o=this.needsLLMCompression(e,t,s.contextWindow),l=s.llmProvider||this.llmProvider,c,u=false;if(o&&l&&s.enableLLMCompression!==false){let d=await this.compressWithLLM(n,t,l,s.model||this.model,i);d?(c=d,u=true):c=this.compressWithRules(n,t,i);}else c=this.compressWithRules(n,t,i);if(this.debug){let d=((1-c.length/r)*100).toFixed(1);m.debug("ToolCompressor",`[${e}] ${r} \u2192 ${c.length} chars (${d}% saved, LLM: ${u})`);}return {content:c,originalLength:r,compressedLength:c.length,strategy:n,usedLLM:u,metadata:i}}extractMetadata(e,t,s){let n={};switch(e){case "file_read":case "file_write":case "file_edit":let r=t.match(/(?:file|path)[:\s]+([^\n]+)/i);r&&(n.filePath=r[1].trim());break;case "bash":let i=t.match(/(?:command|cmd)[:\s]+([^\n]+)/i);i&&(n.command=i[1].trim()),/error|failed|exit code [1-9]/i.test(t)&&(n.exitCode=1);break;case "web_fetch":case "web_search":let o=t.match(/https?:\/\/[^\s\)]+/g);o&&(n.urls=[...new Set(o)].slice(0,10));break}return n}async compressWithLLM(e,t,s,n,r){let i=Av[e];if(!i)return null;try{let l=t.length>8e3?t.slice(0,8e3)+`
1132
1132
 
1133
- ...[\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]...`:t,c=await s.chat([{role:"system",content:i.system},{role:"user",content:i.user(l,r?.filePath)}],{model:n,temperature:.2});return me(c.choices[0]?.message?.content)?.trim()||null}catch(o){return m.warn("ToolCompressor",`LLM compression failed: ${o.message}`),null}}compressWithRules(e,t,s){let n=_v;switch(e){case "file_read":return this.compressFileRead(t,s?.filePath,n);case "file_edit":return this.compressFileEdit(t,n);case "bash":return this.compressBash(t,s?.command,n);case "web_fetch":case "web_search":return this.compressWebContent(t,s?.urls,n);case "file_search":return this.compressSearchResult(t,n);default:return this.truncateWithContext(t,n)}}compressFileRead(e,t,s=2e3){let n=e.split(`
1133
+ ...[\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]...`:t,c=await s.chat([{role:"system",content:i.system},{role:"user",content:i.user(l,r?.filePath)}],{model:n,temperature:.2});return me(c.choices[0]?.message?.content)?.trim()||null}catch(o){return m.warn("ToolCompressor",`LLM compression failed: ${o.message}`),null}}compressWithRules(e,t,s){let n=Rv;switch(e){case "file_read":return this.compressFileRead(t,s?.filePath,n);case "file_edit":return this.compressFileEdit(t,n);case "bash":return this.compressBash(t,s?.command,n);case "web_fetch":case "web_search":return this.compressWebContent(t,s?.urls,n);case "file_search":return this.compressSearchResult(t,n);default:return this.truncateWithContext(t,n)}}compressFileRead(e,t,s=2e3){let n=e.split(`
1134
1134
  `),r=t?`\u{1F4C4} ${t}
1135
1135
  `:"";if(e.length<=s)return r+e;let i=Math.floor(s*.6/80),o=Math.floor(s*.3/80),l=n.slice(0,i).join(`
1136
1136
  `),c=n.slice(-o).join(`
@@ -1160,7 +1160,7 @@ ${t.slice(0,5).map(i=>`- ${i}`).join(`
1160
1160
 
1161
1161
  ... [\u7701\u7565 ${o} \u5B57\u7B26] ...
1162
1162
 
1163
- ${i}`}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}};new as;W();var Av=15,Ev=[/error/i,/错误/,/failed/i,/失败/,/exception/i,/异常/,/❌/,/warning/i,/警告/],fr={system:`\u4F60\u662F\u4E00\u4E2A\u5BF9\u8BDD\u5386\u53F2\u538B\u7F29\u52A9\u624B\u3002\u8BF7\u5C06\u5BF9\u8BDD\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1163
+ ${i}`}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}};new as;W();var Ev=15,Iv=[/error/i,/错误/,/failed/i,/失败/,/exception/i,/异常/,/❌/,/warning/i,/警告/],fr={system:`\u4F60\u662F\u4E00\u4E2A\u5BF9\u8BDD\u5386\u53F2\u538B\u7F29\u52A9\u624B\u3002\u8BF7\u5C06\u5BF9\u8BDD\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1164
1164
  1. \u7528\u6237\u7684\u6838\u5FC3\u9700\u6C42\u548C\u76EE\u6807
1165
1165
  2. \u5173\u952E\u51B3\u7B56\u548C\u5176\u7406\u7531
1166
1166
  3. \u91CD\u8981\u7684\u4EE3\u7801\u53D8\u66F4\uFF08\u6587\u4EF6\u8DEF\u5F84\u3001\u51FD\u6570\u540D\uFF09
@@ -1185,14 +1185,14 @@ ${i}`}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}};new as;W();var A
1185
1185
  - \u4FDD\u7559\u6280\u672F\u7EC6\u8282\uFF08\u6587\u4EF6\u540D\u3001\u51FD\u6570\u540D\u3001\u9519\u8BEF\u4FE1\u606F\uFF09
1186
1186
  - \u603B\u957F\u5EA6\u63A7\u5236\u5728 800 \u5B57\u4EE5\u5185`,user:a=>`\u8BF7\u538B\u7F29\u4EE5\u4E0B\u5BF9\u8BDD\u5386\u53F2:
1187
1187
 
1188
- ${a}`},hn=class{debug;toolCompressor;minRecentMessages;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.toolCompressor=e?.toolCompressor??new as({debug:this.debug}),this.minRecentMessages=e?.minRecentMessages??Av;}async compressMessage(e,t){let s=Et(e),n=this.getMessageType(e);if(n==="system")return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve_system"};if(n==="tool_result"&&e.role==="tool"){let i=e.name||"unknown",o=me(e.content),l=await this.toolCompressor.compress(i,o,t),c={...e,content:l.content},u=Et(c);return {message:c,originalTokens:s,compressedTokens:u,compressionRatio:u/s,usedLLM:l.usedLLM,strategy:`tool_${l.strategy}`}}let r=me(e.content);if(r.length>3e3&&t.llmProvider&&t.enableLLMCompression!==false){let i=await this.compressLongContent(r,t);if(i){let o={...e,content:i},l=Et(o);return {message:o,originalTokens:s,compressedTokens:l,compressionRatio:l/s,usedLLM:true,strategy:"llm_content_compression"}}}return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve"}}async compressMessages(e,t){let s=[],n=tt(e),r=t.tokenBudget||n;return this.debug&&(s.push(`[MessageCompressor] \u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${n} tokens`),s.push(`[MessageCompressor] Token \u9884\u7B97: ${r}`)),n<=r?this.compressLargeMessages(e,t,s):this.compressWithPriority(e,r,t,s)}async compressLargeMessages(e,t,s){let n=tt(e),r=[],i=0,o=0;for(let c of e)if(Et(c)>2e3&&c.role!=="system"){let d=await this.compressMessage(c,t);r.push(d.message),d.usedLLM?i++:d.compressionRatio<1&&o++;}else r.push(c);let l=tt(r);return this.debug&&s.push(`[MessageCompressor] \u5927\u6D88\u606F\u538B\u7F29\u5B8C\u6210: LLM=${i}, \u622A\u65AD=${o}`),{messages:r,originalCount:e.length,compressedCount:r.length,originalTokens:n,compressedTokens:l,savedTokens:n-l,stats:{droppedMessages:0,llmCompressedMessages:i,truncatedMessages:o,preservedMessages:e.length-i-o},debugInfo:this.debug?s:void 0}}async compressWithPriority(e,t,s,n){let r=tt(e),i=this.prioritizeMessages(e);if(this.debug){let w=this.countPriorities(i);n.push(`[MessageCompressor] \u4F18\u5148\u7EA7\u5206\u5E03: CRITICAL=${w.critical}, HIGH=${w.high}, MEDIUM=${w.medium}, LOW=${w.low}`);}let o=[],l=0;for(let w of i)w.priority===0&&(o.push(w),l+=w.tokens);this.debug&&n.push(`[MessageCompressor] CRITICAL \u4FDD\u7559\u540E: ${o.length} \u6761, ${l} tokens`);let c=i.filter(w=>w.priority===1&&!o.includes(w));for(let w of c){let C=await this.compressMessage(w.message,s),k=C.compressedTokens;l+k<=t&&(o.push({...w,message:C.message,tokens:k}),l+=k);}this.debug&&n.push(`[MessageCompressor] HIGH \u4FDD\u7559\u540E: ${o.length} \u6761, ${l} tokens`);let u=t-l,d=i.filter(w=>(w.priority===2||w.priority===3)&&!o.includes(w));if(d.reduce((w,C)=>w+C.tokens,0)<=u)for(let w of d){let C=await this.compressMessage(w.message,s);o.push({...w,message:C.message,tokens:C.compressedTokens}),l+=C.compressedTokens;}else {if(s.llmProvider&&s.enableLLMCompression!==false&&d.length>=5){let w=await this.compressBatchWithLLM(d.map(C=>C.message),s);if(w){let C={role:"user",content:`[\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55]
1189
- ${w}`,name:"CompressedHistory"},k=Et(C);l+k<=t&&(o.push({message:C,priority:2,tokens:k,index:-1,type:"user",reason:"LLM batch compressed"}),l+=k,this.debug&&n.push(`[MessageCompressor] LLM \u6279\u91CF\u538B\u7F29: ${d.length} \u6761 \u2192 1 \u6761\u6458\u8981`));}}if(!o.find(w=>w.reason==="LLM batch compressed")){let w=[...d].sort((C,k)=>k.index-C.index);for(let C of w){let k=await this.compressMessage(C.message,s);l+k.compressedTokens<=t&&(o.push({...C,message:k.message,tokens:k.compressedTokens}),l+=k.compressedTokens);}}}let g=[...o].sort((w,C)=>w.index===-1||C.index===-1?0:w.index-C.index).map(w=>w.message),f=tt(g),b=e.length-o.length,y=o.filter(w=>w.reason.includes("LLM")).length;return this.debug&&(n.push(`[MessageCompressor] \u6700\u7EC8: ${g.length} \u6761, ${f} tokens`),n.push(`[MessageCompressor] \u8282\u7701: ${r-f} tokens`)),{messages:g,originalCount:e.length,compressedCount:g.length,originalTokens:r,compressedTokens:f,savedTokens:r-f,stats:{droppedMessages:b,llmCompressedMessages:y,truncatedMessages:0,preservedMessages:o.length-y},debugInfo:this.debug?n:void 0}}getMessageType(e){return e.role==="system"?"system":e.role==="user"?"user":e.role==="tool"?"tool_result":e.role==="assistant"?e.tool_calls&&e.tool_calls.length>0?"tool_call":"assistant":"user"}prioritizeMessages(e){let t=[];for(let s=0;s<e.length;s++){let n=e[s],r=Et(n),i=this.getMessageType(n),o=e.length-s,l,c;i==="system"?(l=0,c="system message"):o<=this.minRecentMessages?(l=0,c=`recent message (${o} from end)`):this.containsError(n)?(l=1,c="contains error"):i==="tool_call"?(l=1,c="tool calls"):i==="tool_result"?(l=1,c="tool result"):i==="user"?(l=2,c="user message"):i==="assistant"?(l=2,c="assistant message"):(l=3,c="default"),t.push({message:n,priority:l,tokens:r,index:s,type:i,reason:c});}return t}containsError(e){let t=me(e.content);return Ev.some(s=>s.test(t))}countPriorities(e){return {critical:e.filter(t=>t.priority===0).length,high:e.filter(t=>t.priority===1).length,medium:e.filter(t=>t.priority===2).length,low:e.filter(t=>t.priority===3).length}}async compressLongContent(e,t){if(!t.llmProvider)return null;try{let n=/[\u4e00-\u9fa5]/.test(e)?fr.systemZh:fr.system,r=6e3,i=e.length>r?e.slice(0,r)+`
1188
+ ${a}`},hn=class{debug;toolCompressor;minRecentMessages;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.toolCompressor=e?.toolCompressor??new as({debug:this.debug}),this.minRecentMessages=e?.minRecentMessages??Ev;}async compressMessage(e,t){let s=Et(e),n=this.getMessageType(e);if(n==="system")return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve_system"};if(n==="tool_result"&&e.role==="tool"){let i=e.name||"unknown",o=me(e.content),l=await this.toolCompressor.compress(i,o,t),c={...e,content:l.content},u=Et(c);return {message:c,originalTokens:s,compressedTokens:u,compressionRatio:u/s,usedLLM:l.usedLLM,strategy:`tool_${l.strategy}`}}let r=me(e.content);if(r.length>3e3&&t.llmProvider&&t.enableLLMCompression!==false){let i=await this.compressLongContent(r,t);if(i){let o={...e,content:i},l=Et(o);return {message:o,originalTokens:s,compressedTokens:l,compressionRatio:l/s,usedLLM:true,strategy:"llm_content_compression"}}}return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve"}}async compressMessages(e,t){let s=[],n=tt(e),r=t.tokenBudget||n;return this.debug&&(s.push(`[MessageCompressor] \u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${n} tokens`),s.push(`[MessageCompressor] Token \u9884\u7B97: ${r}`)),n<=r?this.compressLargeMessages(e,t,s):this.compressWithPriority(e,r,t,s)}async compressLargeMessages(e,t,s){let n=tt(e),r=[],i=0,o=0;for(let c of e)if(Et(c)>2e3&&c.role!=="system"){let d=await this.compressMessage(c,t);r.push(d.message),d.usedLLM?i++:d.compressionRatio<1&&o++;}else r.push(c);let l=tt(r);return this.debug&&s.push(`[MessageCompressor] \u5927\u6D88\u606F\u538B\u7F29\u5B8C\u6210: LLM=${i}, \u622A\u65AD=${o}`),{messages:r,originalCount:e.length,compressedCount:r.length,originalTokens:n,compressedTokens:l,savedTokens:n-l,stats:{droppedMessages:0,llmCompressedMessages:i,truncatedMessages:o,preservedMessages:e.length-i-o},debugInfo:this.debug?s:void 0}}async compressWithPriority(e,t,s,n){let r=tt(e),i=this.prioritizeMessages(e);if(this.debug){let w=this.countPriorities(i);n.push(`[MessageCompressor] \u4F18\u5148\u7EA7\u5206\u5E03: CRITICAL=${w.critical}, HIGH=${w.high}, MEDIUM=${w.medium}, LOW=${w.low}`);}let o=[],l=0;for(let w of i)w.priority===0&&(o.push(w),l+=w.tokens);this.debug&&n.push(`[MessageCompressor] CRITICAL \u4FDD\u7559\u540E: ${o.length} \u6761, ${l} tokens`);let c=i.filter(w=>w.priority===1&&!o.includes(w));for(let w of c){let C=await this.compressMessage(w.message,s),k=C.compressedTokens;l+k<=t&&(o.push({...w,message:C.message,tokens:k}),l+=k);}this.debug&&n.push(`[MessageCompressor] HIGH \u4FDD\u7559\u540E: ${o.length} \u6761, ${l} tokens`);let u=t-l,d=i.filter(w=>(w.priority===2||w.priority===3)&&!o.includes(w));if(d.reduce((w,C)=>w+C.tokens,0)<=u)for(let w of d){let C=await this.compressMessage(w.message,s);o.push({...w,message:C.message,tokens:C.compressedTokens}),l+=C.compressedTokens;}else {if(s.llmProvider&&s.enableLLMCompression!==false&&d.length>=5){let w=await this.compressBatchWithLLM(d.map(C=>C.message),s);if(w){let C={role:"user",content:`[\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55]
1189
+ ${w}`,name:"CompressedHistory"},k=Et(C);l+k<=t&&(o.push({message:C,priority:2,tokens:k,index:-1,type:"user",reason:"LLM batch compressed"}),l+=k,this.debug&&n.push(`[MessageCompressor] LLM \u6279\u91CF\u538B\u7F29: ${d.length} \u6761 \u2192 1 \u6761\u6458\u8981`));}}if(!o.find(w=>w.reason==="LLM batch compressed")){let w=[...d].sort((C,k)=>k.index-C.index);for(let C of w){let k=await this.compressMessage(C.message,s);l+k.compressedTokens<=t&&(o.push({...C,message:k.message,tokens:k.compressedTokens}),l+=k.compressedTokens);}}}let g=[...o].sort((w,C)=>w.index===-1||C.index===-1?0:w.index-C.index).map(w=>w.message),f=tt(g),b=e.length-o.length,y=o.filter(w=>w.reason.includes("LLM")).length;return this.debug&&(n.push(`[MessageCompressor] \u6700\u7EC8: ${g.length} \u6761, ${f} tokens`),n.push(`[MessageCompressor] \u8282\u7701: ${r-f} tokens`)),{messages:g,originalCount:e.length,compressedCount:g.length,originalTokens:r,compressedTokens:f,savedTokens:r-f,stats:{droppedMessages:b,llmCompressedMessages:y,truncatedMessages:0,preservedMessages:o.length-y},debugInfo:this.debug?n:void 0}}getMessageType(e){return e.role==="system"?"system":e.role==="user"?"user":e.role==="tool"?"tool_result":e.role==="assistant"?e.tool_calls&&e.tool_calls.length>0?"tool_call":"assistant":"user"}prioritizeMessages(e){let t=[];for(let s=0;s<e.length;s++){let n=e[s],r=Et(n),i=this.getMessageType(n),o=e.length-s,l,c;i==="system"?(l=0,c="system message"):o<=this.minRecentMessages?(l=0,c=`recent message (${o} from end)`):this.containsError(n)?(l=1,c="contains error"):i==="tool_call"?(l=1,c="tool calls"):i==="tool_result"?(l=1,c="tool result"):i==="user"?(l=2,c="user message"):i==="assistant"?(l=2,c="assistant message"):(l=3,c="default"),t.push({message:n,priority:l,tokens:r,index:s,type:i,reason:c});}return t}containsError(e){let t=me(e.content);return Iv.some(s=>s.test(t))}countPriorities(e){return {critical:e.filter(t=>t.priority===0).length,high:e.filter(t=>t.priority===1).length,medium:e.filter(t=>t.priority===2).length,low:e.filter(t=>t.priority===3).length}}async compressLongContent(e,t){if(!t.llmProvider)return null;try{let n=/[\u4e00-\u9fa5]/.test(e)?fr.systemZh:fr.system,r=6e3,i=e.length>r?e.slice(0,r)+`
1190
1190
 
1191
1191
  ...[\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]...`:e,o=await t.llmProvider.chat([{role:"system",content:n},{role:"user",content:`\u8BF7\u538B\u7F29\u4EE5\u4E0B\u5185\u5BB9:
1192
1192
 
1193
1193
  ${i}`}],{model:t.model,temperature:.2});return me(o.choices[0]?.message?.content)||null}catch(s){return m.warn("MessageCompressor",`LLM compression failed: ${s.message}`),null}}async compressBatchWithLLM(e,t){if(!t.llmProvider)return null;try{let s=e.map(o=>{let l=o.role==="assistant"?"Assistant":o.role==="user"?"User":o.role==="tool"?"Tool":o.role,c=me(o.content),u=c.length>800?c.slice(0,800)+"...":c;return `[${l}] ${u}`}).join(`
1194
1194
 
1195
- `),r=/[\u4e00-\u9fa5]/.test(s)?fr.systemZh:fr.system,i=await t.llmProvider.chat([{role:"system",content:r},{role:"user",content:fr.user(s)}],{model:t.model,temperature:.3});return me(i.choices[0]?.message?.content)||null}catch(s){return m.warn("MessageCompressor",`Batch LLM compression failed: ${s.message}`),null}}};new hn;var Iv={debug:false,minRecentMessages:15,defaultTokenBudget:1e5,enableLLMCompression:true,llmTimeout:3e4},qi=class{config;toolCompressor;messageCompressor;llmProvider;model;contextWindow;constructor(e){this.config={...Iv,...e},this.config.debug=this.config.debug||process.env.CLI_DEBUG==="1",this.toolCompressor=new as({debug:this.config.debug}),this.messageCompressor=new hn({debug:this.config.debug,toolCompressor:this.toolCompressor,minRecentMessages:this.config.minRecentMessages});}setLLMProvider(e,t){this.llmProvider=e,this.model=t;}setContextWindow(e){this.contextWindow=e,this.config.debug&&m.info("UnifiedCompressor",`Context window set to: ${e}`);}registerToolCompressor(e){m.info("UnifiedCompressor","Custom tool compressor registered");}setMessageCompressor(e){this.messageCompressor=e,m.info("UnifiedCompressor","Custom message compressor set");}async compressHistory(e,t,s){let n=Date.now(),r=tt(e),i={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,tokenBudget:t,contextWindow:s?.contextWindow||this.contextWindow,iteration:s?.iteration,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,signal:s?.signal,debug:this.config.debug};if(this.config.debug&&m.debug("UnifiedCompressor",`\u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${r} tokens \u2192 \u9884\u7B97 ${t} tokens`),r<=t){let c=await this.compressLargeMessagesOnly(e,i);return this.config.debug&&m.debug("UnifiedCompressor",`\u5728\u9884\u7B97\u5185\uFF0C\u4EC5\u538B\u7F29\u5927\u6D88\u606F: ${c.savedTokens} tokens \u8282\u7701`),c}let o=await this.messageCompressor.compressMessages(e,i),l=Date.now()-n;return this.config.debug&&m.debug("UnifiedCompressor",`\u538B\u7F29\u5B8C\u6210 (${l}ms): ${o.originalCount} \u2192 ${o.compressedCount} \u6761, ${o.originalTokens} \u2192 ${o.compressedTokens} tokens (\u8282\u7701 ${o.savedTokens} tokens, ${(o.savedTokens/o.originalTokens*100).toFixed(1)}%)`),o}async compressLargeMessagesOnly(e,t){let s=tt(e),n=[],r=0,i=0;for(let l of e)if(Et(l)>2e3&&l.role!=="system"){let u=await this.messageCompressor.compressMessage(l,t);n.push(u.message),u.usedLLM?r++:u.compressionRatio<1&&i++;}else n.push(l);let o=tt(n);return {messages:n,originalCount:e.length,compressedCount:n.length,originalTokens:s,compressedTokens:o,savedTokens:s-o,stats:{droppedMessages:0,llmCompressedMessages:r,truncatedMessages:i,preservedMessages:e.length-r-i}}}async compressToolResult(e,t,s){let n={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,debug:this.config.debug};return (await this.toolCompressor.compress(e,t,n)).content}getStats(){return {config:this.config,hasLLMProvider:!!this.llmProvider}}};function Mv(a){return a.replace(/\uFEFF/g,"").replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/,\s*([}\]])/g,"$1").trim()}function Pv(a){let e=a.trim();if(!e)return null;let t=e.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);if(t?.[1])return t[1].trim();let s=e.indexOf("{"),n=e.lastIndexOf("}");return s>=0&&n>s?e.slice(s,n+1).trim():null}function xp(a){try{let e=JSON.parse(a);return e&&typeof e=="object"&&!Array.isArray(e)?{ok:!0,value:e}:{ok:!1,error:"arguments should be a JSON object"}}catch(e){return {ok:false,error:e?.message||"invalid JSON"}}}function fn(a){let e=(a||"").trim();if(!e)return {ok:true,args:{},raw:e,normalized:"{}",repaired:false};let t=xp(e);if(t.ok)return {ok:true,args:t.value,raw:e,normalized:e,repaired:false};let s=Pv(e),n=Mv(s||e),r=xp(n);return r.ok?{ok:true,args:r.value,raw:e,normalized:n,repaired:n!==e,reason:t.error}:{ok:false,args:{},raw:e,normalized:n,repaired:n!==e,reason:r.error||t.error}}function Dv(a,e){if(typeof a!="string")return null;let t=a.trim();if(!t.startsWith("{"))return null;try{let s=JSON.parse(t);return !s||typeof s!="object"||s.tool!==e||typeof s.status!="string"?null:s.status}catch{return null}}var zi=class a{static READ_ONLY_TOOLS=new Set(["readfile","search","search_files","list_directory","show_tree","analyze_code","search_symbol","get_definitions","get_references","git_status","git_diff","git_blame","git_branch_list"]);static STATE_MODIFYING_TOOLS=new Set(["write_file","edit_file","create_directory","delete_file","rename_file","apply_patch","execute_shell","execute_bash","execute_python","execute_javascript","git_commit","git_branch","run_tests","run_lint","run_format"]);static TOOL_METADATA=new Map([["readfile",{name:"readfile",isReadOnly:true,category:"read",description:"Read file contents"}],["search",{name:"search",isReadOnly:true,category:"read",description:"Search file contents"}],["search_files",{name:"search_files",isReadOnly:true,category:"read",description:"Search files by name"}],["list_directory",{name:"list_directory",isReadOnly:true,category:"read",description:"List directory contents"}],["show_tree",{name:"show_tree",isReadOnly:true,category:"read",description:"Show directory tree"}],["analyze_code",{name:"analyze_code",isReadOnly:true,category:"read",description:"Analyze code structure"}],["search_symbol",{name:"search_symbol",isReadOnly:true,category:"read",description:"Search symbols in index"}],["get_definitions",{name:"get_definitions",isReadOnly:true,category:"read",description:"Find symbol definitions"}],["get_references",{name:"get_references",isReadOnly:true,category:"read",description:"Find symbol references"}],["git_status",{name:"git_status",isReadOnly:true,category:"read",description:"Show git status"}],["git_diff",{name:"git_diff",isReadOnly:true,category:"read",description:"Show git diff"}],["git_blame",{name:"git_blame",isReadOnly:true,category:"read",description:"Show git blame"}],["git_branch_list",{name:"git_branch_list",isReadOnly:true,category:"read",description:"List git branches"}],["write_file",{name:"write_file",isReadOnly:false,category:"write",description:"Write file"}],["edit_file",{name:"edit_file",isReadOnly:false,category:"write",description:"Edit file"}],["create_directory",{name:"create_directory",isReadOnly:false,category:"write",description:"Create directory"}],["delete_file",{name:"delete_file",isReadOnly:false,category:"write",description:"Delete file"}],["rename_file",{name:"rename_file",isReadOnly:false,category:"write",description:"Rename file"}],["apply_patch",{name:"apply_patch",isReadOnly:false,category:"write",description:"Apply patch"}],["git_commit",{name:"git_commit",isReadOnly:false,category:"write",description:"Git commit"}],["git_branch",{name:"git_branch",isReadOnly:false,category:"write",description:"Git branch"}],["run_tests",{name:"run_tests",isReadOnly:false,category:"execute",description:"Run tests"}],["run_lint",{name:"run_lint",isReadOnly:false,category:"execute",description:"Run lint"}],["run_format",{name:"run_format",isReadOnly:false,category:"execute",description:"Run format"}],["execute_shell",{name:"execute_shell",isReadOnly:false,category:"execute",description:"Execute shell command"}],["execute_bash",{name:"execute_bash",isReadOnly:false,category:"execute",description:"Execute bash script"}],["execute_python",{name:"execute_python",isReadOnly:false,category:"execute",description:"Execute Python code"}],["execute_javascript",{name:"execute_javascript",isReadOnly:false,category:"execute",description:"Execute JavaScript code"}]]);static isReadOnly(e){return a.READ_ONLY_TOOLS.has(e)}static isStateModifying(e){return a.STATE_MODIFYING_TOOLS.has(e)}static getMetadata(e){return a.TOOL_METADATA.get(e)}analyzePlan(e,t,s){let n=[],r=[];for(let i of e){let o=i.function.name,l=t.find(d=>d.name===o),c=s?.parallelSafeTools.has(o)===true;(s?c:l?$i(l)==="safe":a.isReadOnly(o))?n.push(i):r.push(i);}return {parallel:n,sequential:r,totalTools:e.length,parallelCount:n.length,sequentialCount:r.length}}async executeSingleTool(e,t,s){let n=Date.now();if(s?.aborted)return {id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n};let r=t.find(i=>i.name===e.function.name);if(!r)return {id:e.id,name:e.function.name,output:`Error: Tool ${e.function.name} not found`,success:false,executionTime:Date.now()-n};try{let i=fn(e.function.arguments);if(!i.ok)return {id:e.id,name:e.function.name,output:`Error: Invalid JSON arguments for ${e.function.name}: ${i.reason||"parse failed"}`,success:!1,executionTime:Date.now()-n};let o=await r.function(i.args,{signal:s}),l=!0;return Dv(o,e.function.name)==="error"&&(l=!1),s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:!1,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:o,success:l,executionTime:Date.now()-n}}catch(i){return i.name==="AbortError"||s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:`Error: ${i.message}`,success:false,executionTime:Date.now()-n}}}async execute(e,t,s,n){let r=Date.now(),i=Vd(t),o=this.analyzePlan(e,t,i);process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Execution Plan:"),console.log(` Total: ${o.totalTools} tools`),console.log(` Parallel (read-only): ${o.parallelCount} tools`),console.log(` Sequential (state-modifying): ${o.sequentialCount} tools`));let l=new Map,c=0,u=0;if(o.parallel.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${o.parallel.length} read-only tools in parallel...`);let w=o.parallel.map(k=>this.executeSingleTool(k,t,n).then(T=>(s&&s(T),T))),C=await Promise.all(w);c=Date.now()-y;for(let k of C)l.set(k.id,k);process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Parallel execution completed in ${c}ms`);}if(o.sequential.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${o.sequential.length} state-modifying tools sequentially...`);for(let w of o.sequential){if(n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted before ${w.function.name}`);break}let C=await this.executeSingleTool(w,t,n);if(s&&s(C),l.set(C.id,C),n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted after ${w.function.name}`);break}}u=Date.now()-y,process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Sequential execution completed in ${u}ms`);}let d=e.map(y=>{let w=l.get(y.id);return w||{id:y.id,name:y.function.name,output:"Error: Result not found",success:false}}),p=Date.now()-r,h=d.reduce((y,w)=>y+(w.executionTime||0),0),g=h-p,f=h>0?h/p:1,b={totalTime:p,parallelTime:c,sequentialTime:u,timeSaved:g,speedup:f};return process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Performance Stats:"),console.log(` Total time: ${p}ms`),console.log(` Parallel time: ${c}ms`),console.log(` Sequential time: ${u}ms`),console.log(` Estimated sequential time: ${h}ms`),console.log(` Time saved: ${g}ms`),console.log(` Speedup: ${f.toFixed(2)}x`)),{results:d,stats:b}}getToolClassification(e){let t=a.isReadOnly(e),s=a.getMetadata(e);return {isReadOnly:t,category:s?.category||"unknown",canParallel:t}}static canExecuteInParallel(e){return e.every(t=>a.READ_ONLY_TOOLS.has(t))}static getReadOnlyTools(){return Array.from(a.READ_ONLY_TOOLS)}static getStateModifyingTools(){return Array.from(a.STATE_MODIFYING_TOOLS)}};var Es={environment:{zh:a=>`## \u73AF\u5883
1195
+ `),r=/[\u4e00-\u9fa5]/.test(s)?fr.systemZh:fr.system,i=await t.llmProvider.chat([{role:"system",content:r},{role:"user",content:fr.user(s)}],{model:t.model,temperature:.3});return me(i.choices[0]?.message?.content)||null}catch(s){return m.warn("MessageCompressor",`Batch LLM compression failed: ${s.message}`),null}}};new hn;var Mv={debug:false,minRecentMessages:15,defaultTokenBudget:1e5,enableLLMCompression:true,llmTimeout:3e4},qi=class{config;toolCompressor;messageCompressor;llmProvider;model;contextWindow;constructor(e){this.config={...Mv,...e},this.config.debug=this.config.debug||process.env.CLI_DEBUG==="1",this.toolCompressor=new as({debug:this.config.debug}),this.messageCompressor=new hn({debug:this.config.debug,toolCompressor:this.toolCompressor,minRecentMessages:this.config.minRecentMessages});}setLLMProvider(e,t){this.llmProvider=e,this.model=t;}setContextWindow(e){this.contextWindow=e,this.config.debug&&m.info("UnifiedCompressor",`Context window set to: ${e}`);}registerToolCompressor(e){m.info("UnifiedCompressor","Custom tool compressor registered");}setMessageCompressor(e){this.messageCompressor=e,m.info("UnifiedCompressor","Custom message compressor set");}async compressHistory(e,t,s){let n=Date.now(),r=tt(e),i={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,tokenBudget:t,contextWindow:s?.contextWindow||this.contextWindow,iteration:s?.iteration,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,signal:s?.signal,debug:this.config.debug};if(this.config.debug&&m.debug("UnifiedCompressor",`\u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${r} tokens \u2192 \u9884\u7B97 ${t} tokens`),r<=t){let c=await this.compressLargeMessagesOnly(e,i);return this.config.debug&&m.debug("UnifiedCompressor",`\u5728\u9884\u7B97\u5185\uFF0C\u4EC5\u538B\u7F29\u5927\u6D88\u606F: ${c.savedTokens} tokens \u8282\u7701`),c}let o=await this.messageCompressor.compressMessages(e,i),l=Date.now()-n;return this.config.debug&&m.debug("UnifiedCompressor",`\u538B\u7F29\u5B8C\u6210 (${l}ms): ${o.originalCount} \u2192 ${o.compressedCount} \u6761, ${o.originalTokens} \u2192 ${o.compressedTokens} tokens (\u8282\u7701 ${o.savedTokens} tokens, ${(o.savedTokens/o.originalTokens*100).toFixed(1)}%)`),o}async compressLargeMessagesOnly(e,t){let s=tt(e),n=[],r=0,i=0;for(let l of e)if(Et(l)>2e3&&l.role!=="system"){let u=await this.messageCompressor.compressMessage(l,t);n.push(u.message),u.usedLLM?r++:u.compressionRatio<1&&i++;}else n.push(l);let o=tt(n);return {messages:n,originalCount:e.length,compressedCount:n.length,originalTokens:s,compressedTokens:o,savedTokens:s-o,stats:{droppedMessages:0,llmCompressedMessages:r,truncatedMessages:i,preservedMessages:e.length-r-i}}}async compressToolResult(e,t,s){let n={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,debug:this.config.debug};return (await this.toolCompressor.compress(e,t,n)).content}getStats(){return {config:this.config,hasLLMProvider:!!this.llmProvider}}};function Pv(a){return a.replace(/\uFEFF/g,"").replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/,\s*([}\]])/g,"$1").trim()}function Dv(a){let e=a.trim();if(!e)return null;let t=e.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);if(t?.[1])return t[1].trim();let s=e.indexOf("{"),n=e.lastIndexOf("}");return s>=0&&n>s?e.slice(s,n+1).trim():null}function xp(a){try{let e=JSON.parse(a);return e&&typeof e=="object"&&!Array.isArray(e)?{ok:!0,value:e}:{ok:!1,error:"arguments should be a JSON object"}}catch(e){return {ok:false,error:e?.message||"invalid JSON"}}}function fn(a){let e=(a||"").trim();if(!e)return {ok:true,args:{},raw:e,normalized:"{}",repaired:false};let t=xp(e);if(t.ok)return {ok:true,args:t.value,raw:e,normalized:e,repaired:false};let s=Dv(e),n=Pv(s||e),r=xp(n);return r.ok?{ok:true,args:r.value,raw:e,normalized:n,repaired:n!==e,reason:t.error}:{ok:false,args:{},raw:e,normalized:n,repaired:n!==e,reason:r.error||t.error}}function Lv(a,e){if(typeof a!="string")return null;let t=a.trim();if(!t.startsWith("{"))return null;try{let s=JSON.parse(t);return !s||typeof s!="object"||s.tool!==e||typeof s.status!="string"?null:s.status}catch{return null}}var zi=class a{static READ_ONLY_TOOLS=new Set(["readfile","search","search_files","list_directory","show_tree","analyze_code","search_symbol","get_definitions","get_references","git_status","git_diff","git_blame","git_branch_list"]);static STATE_MODIFYING_TOOLS=new Set(["write_file","edit_file","create_directory","delete_file","rename_file","apply_patch","execute_shell","execute_bash","execute_python","execute_javascript","git_commit","git_branch","run_tests","run_lint","run_format"]);static TOOL_METADATA=new Map([["readfile",{name:"readfile",isReadOnly:true,category:"read",description:"Read file contents"}],["search",{name:"search",isReadOnly:true,category:"read",description:"Search file contents"}],["search_files",{name:"search_files",isReadOnly:true,category:"read",description:"Search files by name"}],["list_directory",{name:"list_directory",isReadOnly:true,category:"read",description:"List directory contents"}],["show_tree",{name:"show_tree",isReadOnly:true,category:"read",description:"Show directory tree"}],["analyze_code",{name:"analyze_code",isReadOnly:true,category:"read",description:"Analyze code structure"}],["search_symbol",{name:"search_symbol",isReadOnly:true,category:"read",description:"Search symbols in index"}],["get_definitions",{name:"get_definitions",isReadOnly:true,category:"read",description:"Find symbol definitions"}],["get_references",{name:"get_references",isReadOnly:true,category:"read",description:"Find symbol references"}],["git_status",{name:"git_status",isReadOnly:true,category:"read",description:"Show git status"}],["git_diff",{name:"git_diff",isReadOnly:true,category:"read",description:"Show git diff"}],["git_blame",{name:"git_blame",isReadOnly:true,category:"read",description:"Show git blame"}],["git_branch_list",{name:"git_branch_list",isReadOnly:true,category:"read",description:"List git branches"}],["write_file",{name:"write_file",isReadOnly:false,category:"write",description:"Write file"}],["edit_file",{name:"edit_file",isReadOnly:false,category:"write",description:"Edit file"}],["create_directory",{name:"create_directory",isReadOnly:false,category:"write",description:"Create directory"}],["delete_file",{name:"delete_file",isReadOnly:false,category:"write",description:"Delete file"}],["rename_file",{name:"rename_file",isReadOnly:false,category:"write",description:"Rename file"}],["apply_patch",{name:"apply_patch",isReadOnly:false,category:"write",description:"Apply patch"}],["git_commit",{name:"git_commit",isReadOnly:false,category:"write",description:"Git commit"}],["git_branch",{name:"git_branch",isReadOnly:false,category:"write",description:"Git branch"}],["run_tests",{name:"run_tests",isReadOnly:false,category:"execute",description:"Run tests"}],["run_lint",{name:"run_lint",isReadOnly:false,category:"execute",description:"Run lint"}],["run_format",{name:"run_format",isReadOnly:false,category:"execute",description:"Run format"}],["execute_shell",{name:"execute_shell",isReadOnly:false,category:"execute",description:"Execute shell command"}],["execute_bash",{name:"execute_bash",isReadOnly:false,category:"execute",description:"Execute bash script"}],["execute_python",{name:"execute_python",isReadOnly:false,category:"execute",description:"Execute Python code"}],["execute_javascript",{name:"execute_javascript",isReadOnly:false,category:"execute",description:"Execute JavaScript code"}]]);static isReadOnly(e){return a.READ_ONLY_TOOLS.has(e)}static isStateModifying(e){return a.STATE_MODIFYING_TOOLS.has(e)}static getMetadata(e){return a.TOOL_METADATA.get(e)}analyzePlan(e,t,s){let n=[],r=[];for(let i of e){let o=i.function.name,l=t.find(d=>d.name===o),c=s?.parallelSafeTools.has(o)===true;(s?c:l?$i(l)==="safe":a.isReadOnly(o))?n.push(i):r.push(i);}return {parallel:n,sequential:r,totalTools:e.length,parallelCount:n.length,sequentialCount:r.length}}async executeSingleTool(e,t,s){let n=Date.now();if(s?.aborted)return {id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n};let r=t.find(i=>i.name===e.function.name);if(!r)return {id:e.id,name:e.function.name,output:`Error: Tool ${e.function.name} not found`,success:false,executionTime:Date.now()-n};try{let i=fn(e.function.arguments);if(!i.ok)return {id:e.id,name:e.function.name,output:`Error: Invalid JSON arguments for ${e.function.name}: ${i.reason||"parse failed"}`,success:!1,executionTime:Date.now()-n};let o=await r.function(i.args,{signal:s}),l=!0;return Lv(o,e.function.name)==="error"&&(l=!1),s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:!1,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:o,success:l,executionTime:Date.now()-n}}catch(i){return i.name==="AbortError"||s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:`Error: ${i.message}`,success:false,executionTime:Date.now()-n}}}async execute(e,t,s,n){let r=Date.now(),i=Vd(t),o=this.analyzePlan(e,t,i);process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Execution Plan:"),console.log(` Total: ${o.totalTools} tools`),console.log(` Parallel (read-only): ${o.parallelCount} tools`),console.log(` Sequential (state-modifying): ${o.sequentialCount} tools`));let l=new Map,c=0,u=0;if(o.parallel.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${o.parallel.length} read-only tools in parallel...`);let w=o.parallel.map(k=>this.executeSingleTool(k,t,n).then(T=>(s&&s(T),T))),C=await Promise.all(w);c=Date.now()-y;for(let k of C)l.set(k.id,k);process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Parallel execution completed in ${c}ms`);}if(o.sequential.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${o.sequential.length} state-modifying tools sequentially...`);for(let w of o.sequential){if(n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted before ${w.function.name}`);break}let C=await this.executeSingleTool(w,t,n);if(s&&s(C),l.set(C.id,C),n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted after ${w.function.name}`);break}}u=Date.now()-y,process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Sequential execution completed in ${u}ms`);}let d=e.map(y=>{let w=l.get(y.id);return w||{id:y.id,name:y.function.name,output:"Error: Result not found",success:false}}),p=Date.now()-r,h=d.reduce((y,w)=>y+(w.executionTime||0),0),g=h-p,f=h>0?h/p:1,b={totalTime:p,parallelTime:c,sequentialTime:u,timeSaved:g,speedup:f};return process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Performance Stats:"),console.log(` Total time: ${p}ms`),console.log(` Parallel time: ${c}ms`),console.log(` Sequential time: ${u}ms`),console.log(` Estimated sequential time: ${h}ms`),console.log(` Time saved: ${g}ms`),console.log(` Speedup: ${f.toFixed(2)}x`)),{results:d,stats:b}}getToolClassification(e){let t=a.isReadOnly(e),s=a.getMetadata(e);return {isReadOnly:t,category:s?.category||"unknown",canParallel:t}}static canExecuteInParallel(e){return e.every(t=>a.READ_ONLY_TOOLS.has(t))}static getReadOnlyTools(){return Array.from(a.READ_ONLY_TOOLS)}static getStateModifyingTools(){return Array.from(a.STATE_MODIFYING_TOOLS)}};var Es={environment:{zh:a=>`## \u73AF\u5883
1196
1196
  - \u5DE5\u4F5C\u76EE\u5F55: ${a}
1197
1197
  - Shell \u6BCF\u6B21\u8C03\u7528\u72EC\u7ACB\uFF0Ccd \u4E0D\u8DE8\u8C03\u7528\u6301\u7EED`,en:a=>`## Environment
1198
1198
  - Working directory: ${a}
@@ -1219,7 +1219,7 @@ ${i}`}],{model:t.model,temperature:.2});return me(o.choices[0]?.message?.content
1219
1219
  1. Files >300 lines or 10KB \u2192 Write in chunks, each chunk <200 lines
1220
1220
  2. First step write_file: Create skeleton structure
1221
1221
  3. Subsequent edit_file: Replace section by section (readfile before each edit!)`},toolResults:{zh:'## \u7406\u89E3\u5DE5\u5177\u7ED3\u679C\n\n- `write_file` / `edit_file` \u8FD4\u56DE\u7ED3\u6784\u5316\u7ED3\u679C\uFF1A\n - `"status": "success" + "final": true` \u2192 \u4FEE\u6539\u6210\u529F\uFF0C\u4E0D\u91CD\u590D\u64CD\u4F5C\n - `"status": "already_done"` \u2192 \u5DF2\u5B8C\u6210\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u4E2A\u4EFB\u52A1\n - `"status": "error"` \u2192 \u8BFB\u53D6\u9519\u8BEF\u4FE1\u606F\u5E76\u4FEE\u590D\n- \u4FEE\u6539\u5B8C\u6210\u540E\u4F7F\u7528 `readfile` \u9A8C\u8BC1\u5173\u952E\u51FD\u6570/\u7C7B\u5185\u5BB9\n- readfile \u5931\u8D25 \u2192 \u6269\u5927\u8303\u56F4\u6216\u8C03\u6574\u5173\u952E\u8BCD\uFF0C\u518D\u5C1D\u8BD5',en:'## Understanding Tool Results\n\n- `write_file` / `edit_file` return structured results:\n - `"status": "success" + "final": true` \u2192 Modification successful, don\'t repeat\n - `"status": "already_done"` \u2192 Already complete, proceed to next task\n - `"status": "error"` \u2192 Read error message and fix\n- After modification, use `readfile` to verify key functions/classes\n- readfile fails \u2192 Expand scope or adjust keywords, then retry'},specializedTools:{zh:"## \u4E13\u7528\u5DE5\u5177\n\n- **Git**\uFF1A`git_status` / `git_diff` / `git_blame` / `git_branch_list` / `git_branch` / `git_commit`\n- **\u6587\u4EF6\u64CD\u4F5C**\uFF1A`delete_file` / `rename_file` / `apply_patch`\n- **\u5BFC\u822A**\uFF1A`search_symbol` / `get_definitions` / `get_references`\uFF08\u7D22\u5F15\u53EF\u7528\u65F6\u4F18\u5148\uFF09\n- **\u6D4B\u8BD5**\uFF1A`run_tests` / `run_lint` / `run_format`\uFF08\u907F\u514D\u7528 shell \u4EE3\u66FF\uFF09\n- \u82E5\u89E6\u8FBE\u8FED\u4EE3/\u5DE5\u5177/\u8FD0\u884C\u65F6\u95F4\u9650\u5236\uFF0C\u5148\u603B\u7ED3\u8FDB\u5EA6\u5E76\u8BE2\u95EE\u662F\u5426\u7EE7\u7EED",en:"## Specialized Tools\n\n- **Git**: `git_status` / `git_diff` / `git_blame` / `git_branch_list` / `git_branch` / `git_commit`\n- **File operations**: `delete_file` / `rename_file` / `apply_patch`\n- **Navigation**: `search_symbol` / `get_definitions` / `get_references` (prefer when index available)\n- **Tests**: `run_tests` / `run_lint` / `run_format` (avoid using shell instead)\n- If hitting iteration/tool/runtime limits, summarize progress and ask to continue"},errorRecovery:{zh:"## \u9519\u8BEF\u6062\u590D\n\n- `edit_file` \u5931\u8D25\uFF1A\u91CD\u65B0 `readfile(path, for_edit=true)`\uFF0C\u7F29\u5C0F `old_string`\uFF0C\u5FC5\u8981\u65F6\u52A0 `change_context`\n- \u8FDE\u7EED\u5931\u8D25 2 \u6B21\uFF1A\u6539\u7528 `write_file` \u91CD\u5199\u6574\u4E2A\u6587\u4EF6\n- \u8FDE\u7EED\u5931\u8D25 3 \u6B21\uFF1A\u505C\u6B62\u5F53\u524D\u65B9\u6CD5\uFF0C\u62A5\u544A\u7ED9\u7528\u6237\n- \u7981\u6B62\u4F7F\u7528 sed/awk \u7B49 shell \u547D\u4EE4\u7F16\u8F91\u6587\u4EF6",en:"## Error Recovery\n\n- `edit_file` fails: Re-`readfile(path, for_edit=true)`, reduce `old_string`, add `change_context` if needed\n- 2 consecutive fails: Use `write_file` to rewrite entire file\n- 3 consecutive fails: Stop current approach, report to user\n- Never use sed/awk or other shell commands to edit files"},outputFormat:{zh:"## \u8F93\u51FA\u8981\u6C42\n\n- \u7528\u4E2D\u6587\u56DE\u590D\n- \u64CD\u4F5C\u540E\u7B80\u77ED\u786E\u8BA4\n- \u4E0D\u521B\u5EFA\u7528\u6237\u672A\u8981\u6C42\u7684\u6587\u4EF6\n- \u9047\u5230\u9519\u8BEF\u4F18\u5148\u7528 readfile \u9A8C\u8BC1\uFF0C\u4E0D\u76F2\u76EE\u91CD\u590D\u64CD\u4F5C\n\n### Markdown \u683C\u5F0F\u89C4\u8303\n- \u6807\u9898\u5FC5\u987B\u5728 # \u540E\u52A0\u7A7A\u683C\uFF1A`### \u6807\u9898` \u2713\uFF0C`###\u6807\u9898` \u2717\n- \u7C97\u4F53/\u659C\u4F53\u6807\u8BB0\u4E0E\u6587\u5B57\u4E4B\u95F4\u4E0D\u52A0\u7A7A\u683C\uFF1A`**\u7C97\u4F53**` \u2713\n- \u5217\u8868\u9879 `-` \u540E\u5FC5\u987B\u52A0\u7A7A\u683C\uFF1A`- \u9879\u76EE` \u2713",en:"## Output Requirements\n\n- Reply in English\n- Brief confirmation after operations\n- Don't create unrequested files\n- When encountering errors, verify with readfile first, don't blindly repeat operations\n\n### Markdown Format Rules\n- Headings must have space after #: `### Title` \u2713, `###Title` \u2717\n- Bold/italic markers without space to text: `**bold**` \u2713\n- List items must have space after `-`: `- item` \u2713"}};function Tp(a,e="zh"){let t=[];return t.push(Es.environment[e](a)),t.push(""),t.push(Es.toolUsage[e]),t.push(""),t.push(Es.editRules[e]),t.push(""),t.push(Es.toolResults[e]),t.push(""),t.push(Es.specializedTools[e]),t.push(""),t.push(Es.errorRecovery[e]),t.push(""),t.push(Es.outputFormat[e]),t.join(`
1222
- `)}var Lv={identity:{zh:`\u4F60\u662F Neox AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u5404\u79CD\u4EFB\u52A1\u3002
1222
+ `)}var Ov={identity:{zh:`\u4F60\u662F Neox AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u5404\u79CD\u4EFB\u52A1\u3002
1223
1223
 
1224
1224
  **\u6838\u5FC3\u539F\u5219**\uFF1A
1225
1225
  - \u5FEB\u901F\u7406\u89E3\u7528\u6237\u610F\u56FE
@@ -1265,7 +1265,7 @@ For complex multi-step tasks, use the update_plan tool to create an execution pl
1265
1265
  - Only one step can be in_progress at a time
1266
1266
  - Update plan status as work progresses
1267
1267
 
1268
- Example scenarios: refactoring code, adding features, project migration, performance optimization, etc.`}};function _p(a="zh"){return Lv.identity[a]}function Hi(a){let{workDir:e,language:t="zh"}=a,s=[],n=t==="zh"?`\u5DE5\u4F5C\u76EE\u5F55: ${e}
1268
+ Example scenarios: refactoring code, adding features, project migration, performance optimization, etc.`}};function _p(a="zh"){return Ov.identity[a]}function Hi(a){let{workDir:e,language:t="zh"}=a,s=[],n=t==="zh"?`\u5DE5\u4F5C\u76EE\u5F55: ${e}
1269
1269
  Shell \u6BCF\u6B21\u8C03\u7528\u72EC\u7ACB\uFF0Ccd \u4E0D\u8DE8\u8C03\u7528\u6301\u7EED`:`Working directory: ${e}
1270
1270
  Shell calls are independent; cd does not persist across calls`;s.push(n),s.push(""),s.push(_p(t)),s.push(""),s.push(Tp(e,t)),s.push("");let r=ht.getSkillsForPrompt();if(r){let i=t==="zh"?`## \u53EF\u7528\u6280\u80FD (Skills)
1271
1271
 
@@ -1280,7 +1280,7 @@ Below are registered skills. When user intent matches a skill, use the \`use_ski
1280
1280
  **Important**: Don't ask "do you want to use /commit skill?", instead automatically call \`use_skill\` tool based on user intent.
1281
1281
 
1282
1282
  `;s.push(i+r),s.push("");}return s.push(t==="zh"?"\u5F00\u59CB\u5DE5\u4F5C\u3002":"Start working."),s.join(`
1283
- `)}var Ov=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
1283
+ `)}var Nv=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
1284
1284
 
1285
1285
  ## General
1286
1286
 
@@ -1396,7 +1396,7 @@ You are producing plain text that will later be styled by the CLI. Follow these
1396
1396
  * Optionally include line/column (1\u2011based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
1397
1397
  * Do not use URIs like file://, vscode://, or https://.
1398
1398
  * Do not provide range of lines
1399
- * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;function Ji(a){let{workDir:e,language:t="zh",useCodexStyle:s=false}=a;return s?Ov:Hi({workDir:e,language:t})}function Rp(a,e,t="zh"){return t==="zh"?`\u6587\u4EF6\u7F16\u8F91\u5931\u8D25: ${a}
1399
+ * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;function Ji(a){let{workDir:e,language:t="zh",useCodexStyle:s=false}=a;return s?Nv:Hi({workDir:e,language:t})}function Rp(a,e,t="zh"){return t==="zh"?`\u6587\u4EF6\u7F16\u8F91\u5931\u8D25: ${a}
1400
1400
 
1401
1401
  \u9519\u8BEF\u4FE1\u606F: ${e}
1402
1402
 
@@ -1446,7 +1446,7 @@ Please:
1446
1446
  - Check if the file/path exists
1447
1447
  - Verify your approach
1448
1448
  - Try a different method
1449
- `.trim()};default:return {level:0,shouldTerminate:false,message:""}}}getVerifyCommand(e,t){return e==="readfile"?t?"Use search to locate specific content, or list_directory to check if file exists":"":e==="write_file"||e==="Write"||e==="edit_file"||e==="Edit"?t?`Use readfile "${t}" to verify the changes`:"":e==="search"||e==="search_files"||e==="Glob"?"Try a different search pattern or read the file directly":e==="execute_shell"||e==="execute_bash"||e==="Bash"?"Check the command output from previous calls":""}getAlternativeAction(e,t){return e==="readfile"?"The file content should already be in your context from previous reads - use it directly":e==="write_file"||e==="Write"?"The file was already written - verify with readfile if needed":e==="edit_file"||e==="Edit"?"The edit may have already been applied - use readfile to check current content":e==="search"||e==="search_files"||e==="Glob"?"Search results should already be available - try a different pattern if not found":"Review the output from previous calls before retrying"}getCallCount(e,t){let s=this.hashArgs(e,t);return this.history.filter(n=>n.hash===s).length}reset(){this.history=[],this.interventionCount=0;}getHistory(){return [...this.history]}getRecentDuplicates(){let e=new Map;for(let t of this.history){let s=`${t.toolName}:${t.hash}`;e.set(s,(e.get(s)||0)+1);}return e}};function Ap(){return new xl}var ls=class{config;toolPermissions=new Map;permissionMemory=new Map;constructor(e={}){this.config=e;}setToolPermission(e){this.toolPermissions.set(e.toolName,e);}setToolPermissions(e){e.forEach(t=>this.setToolPermission(t));}async checkPermission(e,t){let s=e.name,n=this.getToolCategory(e),r=this.getToolPermission(e);if(r==="deny")return {allowed:false,source:"config",reason:this.toolPermissions.get(s)?.reason||`Tool "${s}" is denied`};if(r==="allow")return {allowed:true,source:"config"};let i=this.checkMemory(s);if(i)return {allowed:i.decision,source:"remembered",reason:i.decision?void 0:"User previously denied this tool"};if(!this.config.approvalHandler)return {allowed:true,source:"config",reason:"No approval handler configured - auto-approved"};try{let o=this.toolPermissions.get(s),l=await this.config.approvalHandler({toolName:s,toolCategory:n,args:t,reason:o?.reason,allowRemember:o?.allowRemember??!0});return l.remember&&this.saveMemory(s,l.approved),{allowed:l.approved,source:"user",reason:l.approved?void 0:"User denied approval",remember:l.remember}}catch(o){return {allowed:false,source:"config",reason:`Approval handler failed: ${o instanceof Error?o.message:String(o)}`}}}getToolPermission(e){let t=this.toolPermissions.get(e.name);return t?t.permission:e.permission?.defaultPermission?e.permission.defaultPermission:this.config.defaultPermission??"ask"}getToolCategory(e){return e.permission?.category?e.permission.category:this.inferToolCategory(e.name)}inferToolCategory(e){let t=e.toLowerCase();return t.includes("read")||t.includes("grep")||t.includes("glob")||t.includes("search")||t.includes("list")||t.includes("show")?"read":t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("delete")||t.includes("update")?"write":t.includes("bash")||t.includes("exec")||t.includes("run")||t.includes("command")?"execute":t.includes("fetch")||t.includes("request")||t.includes("api")||t.includes("http")||t.includes("download")?"network":"system"}checkMemory(e){let t=this.permissionMemory.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.permissionMemory.delete(e),null):t:null}saveMemory(e,t){let s=this.config.memoryExpirationMs?Date.now()+this.config.memoryExpirationMs:void 0;this.permissionMemory.set(e,{toolName:e,decision:t,timestamp:Date.now(),expiresAt:s});}clearMemory(e){e?this.permissionMemory.delete(e):this.permissionMemory.clear();}setApprovalHandler(e){this.config.approvalHandler=e;}};var $v=[{toolName:"readfile",permission:"allow"},{toolName:"search_symbol",permission:"allow"},{toolName:"get_definitions",permission:"allow"},{toolName:"get_references",permission:"allow"},{toolName:"search",permission:"allow"},{toolName:"search_files",permission:"allow"},{toolName:"list_directory",permission:"allow"},{toolName:"show_tree",permission:"allow"},{toolName:"git_status",permission:"allow"},{toolName:"git_diff",permission:"allow"},{toolName:"git_blame",permission:"allow"},{toolName:"git_branch_list",permission:"allow"},{toolName:"smart_tree",permission:"allow"},{toolName:"analyze_code",permission:"allow"},{toolName:"write_file",permission:"ask",reason:"This will create or overwrite a file",allowRemember:true},{toolName:"edit_file",permission:"ask",reason:"This will modify an existing file",allowRemember:true},{toolName:"create_directory",permission:"ask",reason:"This will create a directory",allowRemember:true},{toolName:"delete_file",permission:"ask",reason:"This will permanently delete files or directories",allowRemember:false},{toolName:"rename_file",permission:"ask",reason:"This will rename or move files or directories",allowRemember:true},{toolName:"apply_patch",permission:"ask",reason:"This will apply a patch to the repository",allowRemember:true},{toolName:"git_branch",permission:"ask",reason:"This will create or switch git branches",allowRemember:true},{toolName:"git_commit",permission:"ask",reason:"This will create a git commit",allowRemember:true},{toolName:"build_index",permission:"ask",reason:"This will build a local code index",allowRemember:true},{toolName:"execute_shell",permission:"ask",reason:"WARNING: running shell commands can modify your system",allowRemember:false},{toolName:"execute_bash",permission:"ask",reason:"WARNING: running shell commands can modify your system",allowRemember:false},{toolName:"execute_python",permission:"ask",reason:"WARNING: executing code can modify files or run external commands",allowRemember:false},{toolName:"execute_javascript",permission:"ask",reason:"WARNING: executing code can modify files or run external commands",allowRemember:false},{toolName:"debug_in_browser",permission:"ask",reason:"WARNING: this will launch a browser session",allowRemember:false},{toolName:"run_tests",permission:"ask",reason:"WARNING: running tests executes project code",allowRemember:false},{toolName:"run_lint",permission:"ask",reason:"WARNING: running lint executes project tools",allowRemember:false},{toolName:"run_format",permission:"ask",reason:"WARNING: running format executes project tools",allowRemember:false},{toolName:"web_fetch",permission:"ask",reason:"This will make a network request",allowRemember:true},{toolName:"web_search",permission:"ask",reason:"This will make a network request",allowRemember:true}];function _l(a){a.setToolPermissions($v);}var cs=class{static strategies=new Map;static register(e){this.strategies.set(e.mode,e);}static getStrategy(e){let t=this.strategies.get(e);if(!t)throw new Error(`No strategy registered for mode: ${e}`);return t}static getAllModes(){return Array.from(this.strategies.keys())}};var yr=class{mode="ask";filterTools(e){return e.filter(t=>this.isReadOnlyTool(t))}getSystemPrompt(){return `You are in ASK mode (read-only). You can:
1449
+ `.trim()};default:return {level:0,shouldTerminate:false,message:""}}}getVerifyCommand(e,t){return e==="readfile"?t?"Use search to locate specific content, or list_directory to check if file exists":"":e==="write_file"||e==="Write"||e==="edit_file"||e==="Edit"?t?`Use readfile "${t}" to verify the changes`:"":e==="search"||e==="search_files"||e==="Glob"?"Try a different search pattern or read the file directly":e==="execute_shell"||e==="execute_bash"||e==="Bash"?"Check the command output from previous calls":""}getAlternativeAction(e,t){return e==="readfile"?"The file content should already be in your context from previous reads - use it directly":e==="write_file"||e==="Write"?"The file was already written - verify with readfile if needed":e==="edit_file"||e==="Edit"?"The edit may have already been applied - use readfile to check current content":e==="search"||e==="search_files"||e==="Glob"?"Search results should already be available - try a different pattern if not found":"Review the output from previous calls before retrying"}getCallCount(e,t){let s=this.hashArgs(e,t);return this.history.filter(n=>n.hash===s).length}reset(){this.history=[],this.interventionCount=0;}getHistory(){return [...this.history]}getRecentDuplicates(){let e=new Map;for(let t of this.history){let s=`${t.toolName}:${t.hash}`;e.set(s,(e.get(s)||0)+1);}return e}};function Ap(){return new xl}var ls=class{config;toolPermissions=new Map;permissionMemory=new Map;constructor(e={}){this.config=e;}setToolPermission(e){this.toolPermissions.set(e.toolName,e);}setToolPermissions(e){e.forEach(t=>this.setToolPermission(t));}async checkPermission(e,t){let s=e.name,n=this.getToolCategory(e),r=this.getToolPermission(e);if(r==="deny")return {allowed:false,source:"config",reason:this.toolPermissions.get(s)?.reason||`Tool "${s}" is denied`};if(r==="allow")return {allowed:true,source:"config"};let i=this.checkMemory(s);if(i)return {allowed:i.decision,source:"remembered",reason:i.decision?void 0:"User previously denied this tool"};if(!this.config.approvalHandler)return {allowed:true,source:"config",reason:"No approval handler configured - auto-approved"};try{let o=this.toolPermissions.get(s),l=await this.config.approvalHandler({toolName:s,toolCategory:n,args:t,reason:o?.reason,allowRemember:o?.allowRemember??!0});return l.remember&&this.saveMemory(s,l.approved),{allowed:l.approved,source:"user",reason:l.approved?void 0:"User denied approval",remember:l.remember}}catch(o){return {allowed:false,source:"config",reason:`Approval handler failed: ${o instanceof Error?o.message:String(o)}`}}}getToolPermission(e){let t=this.toolPermissions.get(e.name);return t?t.permission:e.permission?.defaultPermission?e.permission.defaultPermission:this.config.defaultPermission??"ask"}getToolCategory(e){return e.permission?.category?e.permission.category:this.inferToolCategory(e.name)}inferToolCategory(e){let t=e.toLowerCase();return t.includes("read")||t.includes("grep")||t.includes("glob")||t.includes("search")||t.includes("list")||t.includes("show")?"read":t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("delete")||t.includes("update")?"write":t.includes("bash")||t.includes("exec")||t.includes("run")||t.includes("command")?"execute":t.includes("fetch")||t.includes("request")||t.includes("api")||t.includes("http")||t.includes("download")?"network":"system"}checkMemory(e){let t=this.permissionMemory.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.permissionMemory.delete(e),null):t:null}saveMemory(e,t){let s=this.config.memoryExpirationMs?Date.now()+this.config.memoryExpirationMs:void 0;this.permissionMemory.set(e,{toolName:e,decision:t,timestamp:Date.now(),expiresAt:s});}clearMemory(e){e?this.permissionMemory.delete(e):this.permissionMemory.clear();}setApprovalHandler(e){this.config.approvalHandler=e;}};var Fv=[{toolName:"readfile",permission:"allow"},{toolName:"search_symbol",permission:"allow"},{toolName:"get_definitions",permission:"allow"},{toolName:"get_references",permission:"allow"},{toolName:"search",permission:"allow"},{toolName:"search_files",permission:"allow"},{toolName:"list_directory",permission:"allow"},{toolName:"show_tree",permission:"allow"},{toolName:"git_status",permission:"allow"},{toolName:"git_diff",permission:"allow"},{toolName:"git_blame",permission:"allow"},{toolName:"git_branch_list",permission:"allow"},{toolName:"smart_tree",permission:"allow"},{toolName:"analyze_code",permission:"allow"},{toolName:"write_file",permission:"ask",reason:"This will create or overwrite a file",allowRemember:true},{toolName:"edit_file",permission:"ask",reason:"This will modify an existing file",allowRemember:true},{toolName:"create_directory",permission:"ask",reason:"This will create a directory",allowRemember:true},{toolName:"delete_file",permission:"ask",reason:"This will permanently delete files or directories",allowRemember:false},{toolName:"rename_file",permission:"ask",reason:"This will rename or move files or directories",allowRemember:true},{toolName:"apply_patch",permission:"ask",reason:"This will apply a patch to the repository",allowRemember:true},{toolName:"git_branch",permission:"ask",reason:"This will create or switch git branches",allowRemember:true},{toolName:"git_commit",permission:"ask",reason:"This will create a git commit",allowRemember:true},{toolName:"build_index",permission:"ask",reason:"This will build a local code index",allowRemember:true},{toolName:"execute_shell",permission:"ask",reason:"WARNING: running shell commands can modify your system",allowRemember:false},{toolName:"execute_bash",permission:"ask",reason:"WARNING: running shell commands can modify your system",allowRemember:false},{toolName:"execute_python",permission:"ask",reason:"WARNING: executing code can modify files or run external commands",allowRemember:false},{toolName:"execute_javascript",permission:"ask",reason:"WARNING: executing code can modify files or run external commands",allowRemember:false},{toolName:"debug_in_browser",permission:"ask",reason:"WARNING: this will launch a browser session",allowRemember:false},{toolName:"run_tests",permission:"ask",reason:"WARNING: running tests executes project code",allowRemember:false},{toolName:"run_lint",permission:"ask",reason:"WARNING: running lint executes project tools",allowRemember:false},{toolName:"run_format",permission:"ask",reason:"WARNING: running format executes project tools",allowRemember:false},{toolName:"web_fetch",permission:"ask",reason:"This will make a network request",allowRemember:true},{toolName:"web_search",permission:"ask",reason:"This will make a network request",allowRemember:true}];function _l(a){a.setToolPermissions(Fv);}var cs=class{static strategies=new Map;static register(e){this.strategies.set(e.mode,e);}static getStrategy(e){let t=this.strategies.get(e);if(!t)throw new Error(`No strategy registered for mode: ${e}`);return t}static getAllModes(){return Array.from(this.strategies.keys())}};var yr=class{mode="ask";filterTools(e){return e.filter(t=>this.isReadOnlyTool(t))}getSystemPrompt(){return `You are in ASK mode (read-only). You can:
1450
1450
  - Read files and search code
1451
1451
  - Analyze and understand the codebase
1452
1452
  - Answer questions about the project
@@ -1479,12 +1479,12 @@ All operations will execute automatically without user confirmation. You should:
1479
1479
 
1480
1480
  \u26A0\uFE0F Important: Since there's no approval step, double-check your actions before executing.
1481
1481
 
1482
- Available operations: All tools (auto-approved).`}shouldAutoApprove(){return true}getDescription(){return "Automatic mode - All operations execute without approval (use with caution)"}getIcon(){return "\u26A1"}};cs.register(new yr);cs.register(new br);cs.register(new vr);function Rl(a){return cs.getStrategy(a)}var Ep=2e4,Fv=15e3;function Dp(a,e){let t=process.env[a];if(!t)return e;let s=Number(t);return !Number.isFinite(s)||s<=0?e:Math.floor(s)}function Ip(a,e){let t=a??e;return t===0||t===1/0?null:!Number.isFinite(t)||t<0?e:Math.floor(t)}function Ki(){let a=new Error("Request aborted");return a.name="AbortError",a.code="ERR_CANCELED",a.category="canceled",a}async function Mp(a,e){if(a?.aborted)throw Ki();return e()}function jv(a,e){let t=Math.round(e/1e3),s=new Error(a==="first_chunk"?`Stream timeout: no response for ${t}s`:`Stream timeout: no data for ${t}s`);return s.code="STREAM_TIMEOUT",s.category="retryable_network",s.isNetworkInterrupt=true,s.streamTimeoutPhase=a,s.timeoutMs=e,s}var Bv=Dp("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),Gv=Dp("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),Uv=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function Pp(a,e=Fv){if(!a||a.length<=e)return a;let t=a.split(`
1482
+ Available operations: All tools (auto-approved).`}shouldAutoApprove(){return true}getDescription(){return "Automatic mode - All operations execute without approval (use with caution)"}getIcon(){return "\u26A1"}};cs.register(new yr);cs.register(new br);cs.register(new vr);function Rl(a){return cs.getStrategy(a)}var Ep=2e4,jv=15e3;function Dp(a,e){let t=process.env[a];if(!t)return e;let s=Number(t);return !Number.isFinite(s)||s<=0?e:Math.floor(s)}function Ip(a,e){let t=a??e;return t===0||t===1/0?null:!Number.isFinite(t)||t<0?e:Math.floor(t)}function Ki(){let a=new Error("Request aborted");return a.name="AbortError",a.code="ERR_CANCELED",a.category="canceled",a}async function Mp(a,e){if(a?.aborted)throw Ki();return e()}function Bv(a,e){let t=Math.round(e/1e3),s=new Error(a==="first_chunk"?`Stream timeout: no response for ${t}s`:`Stream timeout: no data for ${t}s`);return s.code="STREAM_TIMEOUT",s.category="retryable_network",s.isNetworkInterrupt=true,s.streamTimeoutPhase=a,s.timeoutMs=e,s}var Gv=Dp("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),Uv=Dp("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),Wv=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function Pp(a,e=jv){if(!a||a.length<=e)return a;let t=a.split(`
1483
1483
  `).length,s=a.length,n=Math.floor(e*.4),r=Math.floor(e*.4),i=n,o=a.length-r;for(;i>0&&(a.charCodeAt(i)&192)===128;)i--;for(;o<a.length&&(a.charCodeAt(o)&192)===128;)o++;let l=a.slice(0,i),c=a.slice(o),d=`
1484
1484
 
1485
1485
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1486
1486
 
1487
- `;return l+d+c}var Vi=class{llmProvider;providerName;model;tools;memory;config;agentName;agentDescription;instructions;contextInjection;userData;plannerMode;inputGuardrails=[];outputGuardrails=[];toolInputGuardrails=[];toolOutputGuardrails=[];structuredOutput;structuredValidator;maxInputTokensOverride;maxInputTokens;minHistoryMessages;parallelExecutor;unifiedCompressor;compressionMode;toolMetricsHistory=[];workspacePath;disableSystemPrompt;enableFGTS;runContext;permissionManager;modeStrategy;currentMode;loopDetector;enablePlanMode;constructor(e){if(this.llmProvider=e.llmProvider,this.providerName=e.providerName,this.model=e.model,this.tools=e.tools,this.memory=e.memory,this.config=e.config,this.agentName=e.agentName||"DefaultAgent",this.agentDescription=e.agentDescription||"",this.instructions=e.instructions,this.contextInjection=e.contextInjection,this.userData=e.userData,this.plannerMode=e.plannerMode??false,this.structuredOutput=e.structuredOutput,this.maxInputTokensOverride=e.maxInputTokensOverride,this.maxInputTokens=this.computeMaxInputTokens(e.contextWindow,e.tailTokenBudget,this.maxInputTokensOverride),this.minHistoryMessages=Math.max(1,e.minHistoryMessages??6),e.structuredOutput&&(this.structuredValidator=new Wi(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new zi,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new qi({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=Rl(this.currentMode),this.permissionManager=e.permissionManager??new ls({defaultPermission:"ask"}),this.loopDetector=Ap(),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=Rl(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??Ep,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??Ep}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Uv){for await(let i of e)yield i;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((i,o)=>{t.aborted?o(Ki()):t.addEventListener("abort",()=>o(Ki()),{once:true});}):null,r=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Ki()}let i=r?Gv:Bv,o=null,l=new Promise((c,u)=>{o=setTimeout(()=>{u(jv(r?"idle":"first_chunk",i));},i);});try{let c=await Promise.race(n?[s.next(),l,n]:[s.next(),l]);if(o&&clearTimeout(o),c.done)return;r=!0,yield c.value;}catch(c){if(o&&clearTimeout(o),s.return)try{await s.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&m.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),s=await this.unifiedCompressor.compressHistory(t,this.maxInputTokens,{iteration:e,enableLLMCompression:true});if(s.stats.droppedMessages>0||s.stats.llmCompressedMessages>0){this.memory.setMessages(s.messages);let n=this.compressionMode==="async"?"Async":"Sync",r=(s.originalTokens/1e3).toFixed(1),i=(s.compressedTokens/1e3).toFixed(1),o=(s.savedTokens/1e3).toFixed(1),l=s.originalCount,c=s.compressedCount;m.info("Context",`[${n}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${r}K \u2192 ${c}\u6761/${i}K (\u8282\u7701 ${o}K, \u4E22\u5F03${s.stats.droppedMessages}\u6761, LLM\u538B\u7F29${s.stats.llmCompressedMessages}\u6761)`),s.debugInfo&&s.debugInfo.forEach(u=>m.debug("Context",u));}return s}setCompressionMode(e){this.compressionMode=e,m.info("Context",`Compression mode set to: ${e}`);}getCompressionMode(){return this.compressionMode}async getInstructions(e){if(typeof this.instructions=="string")return this.instructions;let t={name:this.agentName,description:this.agentDescription};return await this.instructions(e,t)}async getContextInjection(e){if(!this.contextInjection)return null;let s=(typeof this.contextInjection=="string"?this.contextInjection:await this.contextInjection(e,{name:this.agentName,description:this.agentDescription}))?.trim();return s||null}shouldIncludeLastRun(e){let t=e.trim().toLowerCase();return t?/上次|之前|前面|上一步|上轮|继续|回顾|resume|continue|previous|last time/.test(t):false}createRunContext(e,t=0){return {task:e,timestamp:Date.now(),currentTime:new Date,iteration:t,userData:this.userData,systemStatus:void 0}}setUserData(e){this.userData={...this.userData,...e};}async*run(e,t,s){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(m.debug("MK",` hasSignal: ${!!s}`),m.debug("RUNNER","========================================"),m.debug("RUNNER","=== runner.run ENTRY ==="),m.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),m.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),m.debug("RUNNER",` hasSignal: ${!!s}`)),ge.agentStart(e),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let n=this.createRunContext(e,0),r=this.memory.hasConversationMessages?.()??this.memory.getMessagesForLLM().some(I=>I.role==="user"||I.role==="assistant"),i=!r||this.shouldIncludeLastRun(e);n.userData={...n.userData??{},hasConversation:r,includeLastRun:i},this.inputGuardrails.length>0&&(yield {type:"raw_response_event",data:{type:"input_guardrails.check_start",count:this.inputGuardrails.length},event_type:"input_guardrails.check_start"},await Rs.runInputGuardrails(this.inputGuardrails,n,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let o=await this.getInstructions(n),l=await this.getContextInjection(n);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",o?.length||0),console.log("[RUNNER] dynamicInstructions START:",o?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",o?.substring(o.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",o?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",o?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(I=>I.role==="system");if(process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] hasSystemPrompt:",u,"existingMessages count:",c.length),console.log("[RUNNER] disableSystemPrompt:",this.disableSystemPrompt)),this.disableSystemPrompt)u&&this.memory.clear(),o&&this.memory.add({role:"system",content:o});else if(!u){let I=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:I}),this.memory.add({role:"system",content:o}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let A=await al(this.workspacePath);A&&this.memory.add({role:"system",content:A});}catch{}}if(l?this.memory.upsertSystemTagged?this.memory.upsertSystemTagged("context_injection",l):u||this.memory.add({role:"system",content:l}):this.memory.removeSystemTagged?.("context_injection"),t&&t.length>0){let I=[{type:"text",text:e},...t.map(A=>({type:"image_url",image_url:{url:A,detail:"auto"}}))];this.memory.add({role:"user",content:I});}else this.memory.add({role:"user",content:e});let d=Date.now(),p=0,h="",g=0,f={totalTokens:0,promptTokens:0,completionTokens:0},b=false,y=0,w=null,C=new Map,k=0,T=0,_=[],M=this.isExecutionOrientedTask(e),F=0,x=Kt.streamMaxRetries,R=false,j=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:mp,v=j===0||j===1/0,E=Ip(this.config.maxToolCalls,gp),L=Ip(this.config.maxRuntimeMs,hp);for(;v||p<j;){if(s?.aborted){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if(L!==null&&Date.now()-d>=L){w="runtime_limit",b=true,yield {type:"error",error:`Reached max runtime (${nt(L)}). Please summarize progress and ask whether to continue.`};break}if(E!==null&&g>=E){w="tool_call_limit",b=true,yield {type:"error",error:`Reached max tool calls (${E}). Please summarize progress and ask whether to continue.`};break}p++;let I=null;if(this.maxInputTokens){let O=tt(this.memory.getMessagesForLLM()),$=this.maxInputTokens*.97;O>$&&(I=await this.applyContextWindow(p));}I&&(I.stats.droppedMessages>0||I.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:I.originalCount,keptMessages:I.messages.length,droppedMessages:I.stats.droppedMessages,compressedMessages:I.stats.llmCompressedMessages,originalTokens:I.originalTokens,finalTokens:I.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:I.stats.llmCompressedMessages>0,timestamp:Date.now()});let A=this.memory.checkContextHealth();if((A.warnings.length>0||A.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:A.totalTokens,toolResultTokens:A.toolResultTokens,toolResultRatio:A.toolResultRatio,messageCount:A.messageCount,toolMessageCount:A.toolMessageCount,warnings:A.warnings,shouldCompress:A.shouldCompress,shouldCleanup:A.shouldCleanup,byType:A.byType},event_type:"context_health"},A.shouldCleanup&&A.byType.ephemeral.count>5)){let O=this.memory.cleanupEphemeral();O>0&&m.info("Runner",`Cleaned ${O} ephemeral messages`);}m.debug("Runner",this.memory.getTokenSummary()),ge.agentIteration(p,"thinking"),yield {type:"iteration_start",iteration:p};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let O=this.memory.getMessagesForLLM();if(m.info("LLM",`Request: model=${this.model}, messages=${O.length}, tools=${this.tools.length}`),m.debug("LLM","Request messages",{messageCount:O.length,lastMessage:O[O.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let z=O.filter(J=>J.role==="system");console.log("[RUNNER] System messages count:",z.length);for(let J=0;J<z.length;J++){let ie=z[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=[],q=[],oe="",ue={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let z of this.withStreamWatchdog(P,s)){if(z.type==="stream_retry"){R=!0,yield z;continue}if(z.type==="stream_recovered"){yield {type:"stream_recovered",attempt:z.attempt,maxRetries:z.maxRetries};continue}yield {type:"raw_response_event",data:z,event_type:z.choices?.[0]?.delta?"response.delta":"response.chunk"};let J=z.choices?.[0]?.delta;if(z.usage){ue={prompt_tokens:z.usage.prompt_tokens||ue.prompt_tokens,completion_tokens:z.usage.completion_tokens||ue.completion_tokens,total_tokens:z.usage.total_tokens||ue.total_tokens,cached_tokens:z.usage.cached_tokens,cache_read_input_tokens:z.usage.cache_read_input_tokens,cache_creation_input_tokens:z.usage.cache_creation_input_tokens,prompt_tokens_details:z.usage.prompt_tokens_details},f={promptTokens:ue.prompt_tokens,completionTokens:ue.completion_tokens,totalTokens:ue.total_tokens};let ie=!!z.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;q[K]||(q[K]={id:ie.id||`call_${Math.floor(Date.now())}_${K}`,type:"function",function:{name:"",arguments:""}}),ie.id&&(q[K].id=ie.id),ie.function?.name&&(q[K].function.name=ie.function.name),ie.function?.arguments&&(q[K].function.arguments+=ie.function.arguments,yield {type:"tool_call_delta",id:q[K].id,name:q[K].function.name,arguments_delta:ie.function.arguments}),ie.thoughtSignature&&(q[K].thoughtSignature=ie.thoughtSignature);}z.choices?.[0]?.finish_reason&&(oe=z.choices[0].finish_reason),z.thinking_blocks&&Array.isArray(z.thinking_blocks)&&(G=z.thinking_blocks.map(ie=>({type:ie.type,thinking:ie.thinking,signature:ie.signature,data:ie.data})));}}N&&(yield {type:"text_done"}),process.env.CLI_DEBUG_CONSOLE==="1"&&process.env.NEOX_UI_MODE==="1"&&console.log("[Runner] \u{1F3AF} Emitting response.completed event (after LLM response)"),yield {type:"raw_response_event",data:{type:"response.completed"},event_type:"response.completed"};let Se={role:"assistant",content:(N||"").trimEnd()};if(D&&(Se.reasoning_content=D),G.length>0&&(Se.thinking_blocks=G),q.length>0&&(Se.tool_calls=q.map(z=>({...z,function:{...z.function,arguments:z.function.arguments}}))),this.memory.add(Se),process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${q.length}, fullContent.length=${N.length}`),q.length>0){let z=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let S of q){let U=S.function.arguments||"";if(z.test(U)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${S.function.name}`),console.error(`[Runner] Arguments preview: ${U.substring(0,500)}`),yield {type:"raw_response_event",data:{type:"error.placeholder_detected",message:"Model generated placeholder string instead of actual content. This usually happens when the model sees truncated data in conversation history.",tool:S.function.name},event_type:"error.placeholder_detected"},yield {type:"error",error:'Error: Model attempted to write placeholder text ("[omitted ...]") instead of actual content. This happens when conversation history contains truncated data. Please start a new conversation.'},b=!0;break}}if(b)break;if(E!==null&&g+q.length>E){w="tool_call_limit",b=!0,yield {type:"error",error:`Tool call budget exceeded (max ${E}, requested ${q.length}). Please summarize progress and ask whether to continue.`};break}if(q.length>1){let S=q.map(Z=>Z.function.name),U=[...new Set(S)];U.length===1&&S.length>1?m.info("RUNNER",`\u{1F504} Parallel calls: ${S.length}x ${U[0]} (different parameters)`):m.info("RUNNER",`\u{1F504} Parallel calls: ${S.join(", ")}`);}let J=new Map;for(let S of q)J.set(S.id,fn(S.function.arguments));for(let S of q){g++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:S.id,name:S.function.name,arguments:S.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:S.id,name:S.function.name};let Z=J.get(S.id),H=Z?.ok??!1;H?Z?.repaired&&m.warn("RUNNER","Tool arguments repaired from non-standard JSON",{tool:S.function.name,callId:S.id}):ge.toolError(S.function.name,`Invalid JSON arguments (${Z?.reason||"parse failed"}): ${S.function.arguments.substring(0,200)}...`),yield {type:"tool_call_done",id:S.id,name:S.function.name,arguments:S.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:S.id,name:S.function.name,arguments:S.function.arguments},event_type:"response.function_call_arguments.done"};}let ie=new Set,K=null,xe=q.length>1;process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`Processing ${q.length} tool call(s)`,{isParallel:xe,tools:q.map(S=>S.function.name)});for(let S of q){let U=J.get(S.id);if(!U?.ok){let de=`Invalid JSON arguments for tool "${S.function.name}": ${U?.reason||"parse failed"}. Return strict JSON object arguments.`;yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:de,success:!1},this.memory.addToolResult(S.id,S.function.name,de),this.loopDetector.updateLastStatus("error"),ie.add(S.id);continue}let Z=U.args,H=this.loopDetector.detect(S.function.name,Z);if(this.loopDetector.record(S.function.name,Z),H===0)continue;let se=this.loopDetector.generateIntervention(H,S.function.name,Z);if(this.memory.add({role:"system",content:se.message}),H===2&&ru(S.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:se.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:se.message,success:!1},this.memory.addToolResult(S.id,S.function.name,se.message),this.loopDetector.updateLastStatus("error"),ie.add(S.id),se.shouldTerminate){K=se;break}}if(K&&(yield {type:"error",error:K.message},b=!0),b)break;let ee=ie.size>0?q.filter(S=>!ie.has(S.id)):q,fe=new Set(this.modeStrategy.filterTools(this.tools).map(S=>S.name)),ne=S=>S.replace(/["\s/>]+$/g,"").trim(),le=[];for(let S of ee){let U=ne(S.function.name);if(fe.has(U)||fe.has(S.function.name)){le.push(S);continue}let Z=`Tool "${S.function.name}" is not allowed in ${this.currentMode} mode`;ge.toolError(S.function.name,Z),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:Z,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:Z,success:!1},this.memory.addToolResult(S.id,S.function.name,Z),m.info("PERMISSION",`Tool blocked by mode: ${S.function.name} - ${Z}`);}if(le.length===0)continue;let Q=le.map(S=>({id:S.id,type:"function",function:{name:S.function.name,arguments:(()=>{let U=J.get(S.id);return U?.ok?JSON.stringify(U.args):S.function.arguments})()}})),Be=!1;if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${Q.length}`),!this.modeStrategy.shouldAutoApprove()){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se=this.tools.find(Y=>Y.name===U.function.name);if(!se){m.warn("RUNNER",`Tool not found: ${U.function.name}`);continue}let be=await Mp(s,async()=>this.permissionManager.checkPermission(se,H));if(!be.allowed){S.add(U.id);let Y=be.reason||`Tool "${U.function.name}" was denied`;ge.toolError(U.function.name,Y),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:Y,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:Y,success:!1};let Ae=JSON.stringify({type:"ephemeral",status:"error",tool:U.function.name,summary:"Tool execution denied by user",error:Y,final:!0});this.memory.addToolResult(U.id,U.function.name,Ae),m.info("PERMISSION",`Tool denied: ${U.function.name} - ${Y}`),Be=!0;}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;ge.toolError(U.function.name,Z?.message||"permission check failed");}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during permission check"),b=!0;break}throw U}if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Be){m.info("RUNNER","User denied tool - terminating current turn");break}if(Q.length===0)continue}if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${Q.length}, userDeniedTool=${Be}`),this.toolInputGuardrails.length>0){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se={tool_name:U.function.name,tool_input:H,tool_call_id:U.id},be=this.tools.find(de=>de.name===U.function.name);if(!be)continue;this.runContext.iteration=p;let Y=await Mp(s,async()=>Rs.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:se,agent_name:this.agentName,tool:be}));if(!Y.should_execute){S.add(U.id);let de=Y.rejection_message||`Tool ${U.function.name} was blocked by guardrail`;ge.toolError(U.function.name,`Blocked by guardrail: ${de}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:de,success:!1},this.memory.addToolResult(U.id,U.function.name,de),bl(this.runContext,U.function.name,H,!1);}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;if(Z instanceof yt){ge.toolError(U.function.name,`Guardrail tripwire triggered: ${Z.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${U.function.name}: ${Z.message}`},b=!0;break}ge.toolError(U.function.name,`Guardrail check failed: ${Z?.message}`);}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during guardrails check"),b=!0;break}throw U}if(b)break;if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Q.length===0)continue}process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${Q.length}`);let qe=await this.parallelExecutor.execute(Q,this.tools,S=>{if(ge.toolCall(S.name,{}),S.success){let Z=typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length;ge.toolResult(S.name,!0,Z,S.executionTime||0);}else ge.toolError(S.name,S.output);let U={type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()};},s),B=0,re=0,V=0,pe=!1;for(let S of qe.results){if(this.toolMetricsHistory.push({name:S.name,duration:S.executionTime||0,success:S.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.name,output:S.output,success:S.success},(S.name==="update_plan"||S.name==="call_tool")&&S.success)try{m.info("PLAN_UPDATE","\u{1F525} Detected plan-related tool call",{resultId:S.id,toolName:S.name,toolCallsCount:q.length});let Y=q.find(de=>de.id===S.id);if(Y){m.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:Y.id,argsLength:Y.function.arguments?.length});let de=fn(Y.function.arguments||"{}");if(!de.ok)throw new Error(de.reason||"Invalid update_plan arguments");let Ae=de.args,et=null;if(S.name==="update_plan"?et=Ae:S.name==="call_tool"&&Ae?.name==="update_plan"&&(et=Ae.args),!et||!Array.isArray(et.plan))m.debug("PLAN_UPDATE","Skip non-update_plan call_tool",{resultId:S.id,toolName:S.name,callToolName:Ae?.name});else {let An=!0;if(typeof S.output=="string")try{let gs=JSON.parse(S.output);gs&&typeof gs=="object"&&"success"in gs&&(An=gs.success!==!1);}catch{}An?(m.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!et.explanation,planSteps:et.plan?.length}),yield {type:"plan_update",explanation:et.explanation,plan:et.plan,timestamp:Date.now()},m.info("PLAN_UPDATE","\u2705 Emitted plan_update event")):m.warn("PLAN_UPDATE","Skip failed update_plan output",{resultId:S.id});}}else m.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:S.id,availableIds:q.map(de=>de.id)});}catch(Y){m.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:Y});}let Z=typeof S.output=="string"?Pp(S.output):Pp(JSON.stringify(S.output));Z=this.enrichToolResult(Z,S.name,S.executionTime||0);let H=q.find(Y=>Y.id===S.id),se={};if(H){let Y=fn(H.function.arguments||"{}");Y.ok&&(se=Y.args);}if(this.toolOutputGuardrails.length>0)try{let Y=this.tools.find(de=>de.name===S.name);if(Y){let de={tool_name:S.name,tool_input:se,tool_call_id:S.id},Ae=await Rs.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:de,agent_name:this.agentName,tool:Y,output:S.output});Ae.should_use_output||(Z=Ae.replacement_message||"[Output blocked by guardrail]",ge.toolError(S.name,"Output blocked by guardrail"));}}catch(Y){Y instanceof yt&&ge.toolError(S.name,`Output guardrail tripwire triggered: ${Y.message}`);}if(!S.success&&typeof S.output=="string"){let Y=S.output.toLowerCase();if(Y.includes("operation cancelled")||Y.includes("command interrupted")||Y.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),m.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),b=!0;break}}bl(this.runContext,S.name,se,S.success),m.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${S.name}`,{toolName:S.name,success:S.success,rawLength:typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length,truncatedLength:Z.length,outputPreview:Z.substring(0,500)}),this.memory.addToolResult(S.id,S.name,Z);let be=S.success?"success":"error";try{let Y=typeof S.output=="string"?S.output:JSON.stringify(S.output),de=JSON.parse(Y);de.status==="already_done"?be="already_done":de.status==="success"?be="success":de.status==="error"&&(be="error");}catch{}if(this.loopDetector.updateLastStatus(be),_.push({iteration:p,name:S.name,status:be,executionTime:S.executionTime||0}),_.length>24&&_.shift(),be==="error"?re++:be==="already_done"?(V++,this.isVerificationTool(S.name)&&(pe=!0)):(B++,this.isVerificationTool(S.name)&&(pe=!0)),be==="error"){let Y=(C.get(S.name)||0)+1;if(C.set(S.name,Y),S.name==="edit_file"&&(Y===2||Y===3)){let de=typeof S.output=="string"?S.output:JSON.stringify(S.output),Ae=S.name,et=Rp(Ae,de);this.memory.add({role:"system",content:et});}}else C.set(S.name,0);}if(p>0&&p%5===0){let S=this.buildPerformanceHint();S&&(this.memory.add({role:"system",content:S}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",S));}let Re=B+V>0;if(k=re>0&&!Re?k+1:0,process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Iteration quality",{iteration:p,executionTask:M,success:B,alreadyDone:V,error:re,lowProgressStreak:k,verificationSuccess:pe}),M&&k>=2&&(this.memory.add({role:"system",content:this.buildLowProgressReplanPrompt(k)}),T++,k=0,yield {type:"raw_response_event",data:{type:"loop.progress_gate",iteration:p,reason:"low_progress",nudgeCount:T},event_type:"loop.progress_gate"}),process.env.CLI_DEBUG_CONSOLE==="1"&&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: ${q.length}`),m.info("RUNNER",`Iteration: ${p}`)),this.structuredValidator){let J=this.structuredValidator.validate(N);if(J.ok)h=J.normalized||N,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:h,parsed:J.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:J.reason,message:J.message,errors:J.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(J)}),h="";continue}}else h=N;this.outputGuardrails.length>0&&h&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Rs.runOutputGuardrails(this.outputGuardrails,n,this.agentName,h),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});let z=this.evaluateCompletionEvidence(M,g,_);if(!z.ok){T++,this.memory.add({role:"system",content:this.buildEvidenceRequiredPrompt(z.reason)}),process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Completion blocked: missing evidence",{iteration:p,reason:z.reason,nudgeCount:T}),yield {type:"raw_response_event",data:{type:"loop.completion_gate",iteration:p,reason:z.reason,nudgeCount:T},event_type:"loop.completion_gate"};continue}break}}catch(O){if(O?.type==="stream_retry"){R=true,yield O;continue}let $=O instanceof Ce?O:ft(O);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:$.category,code:$.code,retryable:$.retryable,message:$.message}),$.category==="canceled"){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if($.retryable&&F<x&&!R){F++;let G=hr($.category,F,$.retryAfter),q=$.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:q,isStreamTimeout:oe,isNetworkError:ue},event_type:"runner.stream_retry"},await gn(G),p--;continue}let P=Gi($),N=$.message;P&&!N.includes(P)&&(N=`${N}
1487
+ `;return l+d+c}var Vi=class{llmProvider;providerName;model;tools;memory;config;agentName;agentDescription;instructions;contextInjection;userData;plannerMode;inputGuardrails=[];outputGuardrails=[];toolInputGuardrails=[];toolOutputGuardrails=[];structuredOutput;structuredValidator;maxInputTokensOverride;maxInputTokens;minHistoryMessages;parallelExecutor;unifiedCompressor;compressionMode;toolMetricsHistory=[];workspacePath;disableSystemPrompt;enableFGTS;runContext;permissionManager;modeStrategy;currentMode;loopDetector;enablePlanMode;constructor(e){if(this.llmProvider=e.llmProvider,this.providerName=e.providerName,this.model=e.model,this.tools=e.tools,this.memory=e.memory,this.config=e.config,this.agentName=e.agentName||"DefaultAgent",this.agentDescription=e.agentDescription||"",this.instructions=e.instructions,this.contextInjection=e.contextInjection,this.userData=e.userData,this.plannerMode=e.plannerMode??false,this.structuredOutput=e.structuredOutput,this.maxInputTokensOverride=e.maxInputTokensOverride,this.maxInputTokens=this.computeMaxInputTokens(e.contextWindow,e.tailTokenBudget,this.maxInputTokensOverride),this.minHistoryMessages=Math.max(1,e.minHistoryMessages??6),e.structuredOutput&&(this.structuredValidator=new Wi(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new zi,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new qi({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=Rl(this.currentMode),this.permissionManager=e.permissionManager??new ls({defaultPermission:"ask"}),this.loopDetector=Ap(),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=Rl(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??Ep,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??Ep}, 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(Ki()):t.addEventListener("abort",()=>o(Ki()),{once:true});}):null,r=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Ki()}let i=r?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 Rs.runInputGuardrails(this.inputGuardrails,n,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let o=await this.getInstructions(n),l=await this.getContextInjection(n);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",o?.length||0),console.log("[RUNNER] dynamicInstructions START:",o?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",o?.substring(o.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",o?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",o?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(I=>I.role==="system");if(process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] hasSystemPrompt:",u,"existingMessages count:",c.length),console.log("[RUNNER] disableSystemPrompt:",this.disableSystemPrompt)),this.disableSystemPrompt)u&&this.memory.clear(),o&&this.memory.add({role:"system",content:o});else if(!u){let I=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:I}),this.memory.add({role:"system",content:o}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let A=await al(this.workspacePath);A&&this.memory.add({role:"system",content:A});}catch{}}if(l?this.memory.upsertSystemTagged?this.memory.upsertSystemTagged("context_injection",l):u||this.memory.add({role:"system",content:l}):this.memory.removeSystemTagged?.("context_injection"),t&&t.length>0){let I=[{type:"text",text:e},...t.map(A=>({type:"image_url",image_url:{url:A,detail:"auto"}}))];this.memory.add({role:"user",content:I});}else this.memory.add({role:"user",content:e});let d=Date.now(),p=0,h="",g=0,f={totalTokens:0,promptTokens:0,completionTokens:0},b=false,y=0,w=null,C=new Map,k=0,T=0,_=[],M=this.isExecutionOrientedTask(e),F=0,x=Kt.streamMaxRetries,R=false,j=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:mp,v=j===0||j===1/0,E=Ip(this.config.maxToolCalls,gp),L=Ip(this.config.maxRuntimeMs,hp);for(;v||p<j;){if(s?.aborted){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if(L!==null&&Date.now()-d>=L){w="runtime_limit",b=true,yield {type:"error",error:`Reached max runtime (${nt(L)}). Please summarize progress and ask whether to continue.`};break}if(E!==null&&g>=E){w="tool_call_limit",b=true,yield {type:"error",error:`Reached max tool calls (${E}). Please summarize progress and ask whether to continue.`};break}p++;let I=null;if(this.maxInputTokens){let O=tt(this.memory.getMessagesForLLM()),$=this.maxInputTokens*.97;O>$&&(I=await this.applyContextWindow(p));}I&&(I.stats.droppedMessages>0||I.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:I.originalCount,keptMessages:I.messages.length,droppedMessages:I.stats.droppedMessages,compressedMessages:I.stats.llmCompressedMessages,originalTokens:I.originalTokens,finalTokens:I.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:I.stats.llmCompressedMessages>0,timestamp:Date.now()});let A=this.memory.checkContextHealth();if((A.warnings.length>0||A.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:A.totalTokens,toolResultTokens:A.toolResultTokens,toolResultRatio:A.toolResultRatio,messageCount:A.messageCount,toolMessageCount:A.toolMessageCount,warnings:A.warnings,shouldCompress:A.shouldCompress,shouldCleanup:A.shouldCleanup,byType:A.byType},event_type:"context_health"},A.shouldCleanup&&A.byType.ephemeral.count>5)){let O=this.memory.cleanupEphemeral();O>0&&m.info("Runner",`Cleaned ${O} ephemeral messages`);}m.debug("Runner",this.memory.getTokenSummary()),ge.agentIteration(p,"thinking"),yield {type:"iteration_start",iteration:p};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let O=this.memory.getMessagesForLLM();if(m.info("LLM",`Request: model=${this.model}, messages=${O.length}, tools=${this.tools.length}`),m.debug("LLM","Request messages",{messageCount:O.length,lastMessage:O[O.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let z=O.filter(J=>J.role==="system");console.log("[RUNNER] System messages count:",z.length);for(let J=0;J<z.length;J++){let ie=z[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=[],q=[],oe="",ue={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let z of this.withStreamWatchdog(P,s)){if(z.type==="stream_retry"){R=!0,yield z;continue}if(z.type==="stream_recovered"){yield {type:"stream_recovered",attempt:z.attempt,maxRetries:z.maxRetries};continue}yield {type:"raw_response_event",data:z,event_type:z.choices?.[0]?.delta?"response.delta":"response.chunk"};let J=z.choices?.[0]?.delta;if(z.usage){ue={prompt_tokens:z.usage.prompt_tokens||ue.prompt_tokens,completion_tokens:z.usage.completion_tokens||ue.completion_tokens,total_tokens:z.usage.total_tokens||ue.total_tokens,cached_tokens:z.usage.cached_tokens,cache_read_input_tokens:z.usage.cache_read_input_tokens,cache_creation_input_tokens:z.usage.cache_creation_input_tokens,prompt_tokens_details:z.usage.prompt_tokens_details},f={promptTokens:ue.prompt_tokens,completionTokens:ue.completion_tokens,totalTokens:ue.total_tokens};let ie=!!z.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;q[K]||(q[K]={id:ie.id||`call_${Math.floor(Date.now())}_${K}`,type:"function",function:{name:"",arguments:""}}),ie.id&&(q[K].id=ie.id),ie.function?.name&&(q[K].function.name=ie.function.name),ie.function?.arguments&&(q[K].function.arguments+=ie.function.arguments,yield {type:"tool_call_delta",id:q[K].id,name:q[K].function.name,arguments_delta:ie.function.arguments}),ie.thoughtSignature&&(q[K].thoughtSignature=ie.thoughtSignature);}z.choices?.[0]?.finish_reason&&(oe=z.choices[0].finish_reason),z.thinking_blocks&&Array.isArray(z.thinking_blocks)&&(G=z.thinking_blocks.map(ie=>({type:ie.type,thinking:ie.thinking,signature:ie.signature,data:ie.data})));}}N&&(yield {type:"text_done"}),process.env.CLI_DEBUG_CONSOLE==="1"&&process.env.NEOX_UI_MODE==="1"&&console.log("[Runner] \u{1F3AF} Emitting response.completed event (after LLM response)"),yield {type:"raw_response_event",data:{type:"response.completed"},event_type:"response.completed"};let Se={role:"assistant",content:(N||"").trimEnd()};if(D&&(Se.reasoning_content=D),G.length>0&&(Se.thinking_blocks=G),q.length>0&&(Se.tool_calls=q.map(z=>({...z,function:{...z.function,arguments:z.function.arguments}}))),this.memory.add(Se),process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${q.length}, fullContent.length=${N.length}`),q.length>0){let z=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let S of q){let U=S.function.arguments||"";if(z.test(U)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${S.function.name}`),console.error(`[Runner] Arguments preview: ${U.substring(0,500)}`),yield {type:"raw_response_event",data:{type:"error.placeholder_detected",message:"Model generated placeholder string instead of actual content. This usually happens when the model sees truncated data in conversation history.",tool:S.function.name},event_type:"error.placeholder_detected"},yield {type:"error",error:'Error: Model attempted to write placeholder text ("[omitted ...]") instead of actual content. This happens when conversation history contains truncated data. Please start a new conversation.'},b=!0;break}}if(b)break;if(E!==null&&g+q.length>E){w="tool_call_limit",b=!0,yield {type:"error",error:`Tool call budget exceeded (max ${E}, requested ${q.length}). Please summarize progress and ask whether to continue.`};break}if(q.length>1){let S=q.map(Z=>Z.function.name),U=[...new Set(S)];U.length===1&&S.length>1?m.info("RUNNER",`\u{1F504} Parallel calls: ${S.length}x ${U[0]} (different parameters)`):m.info("RUNNER",`\u{1F504} Parallel calls: ${S.join(", ")}`);}let J=new Map;for(let S of q)J.set(S.id,fn(S.function.arguments));for(let S of q){g++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:S.id,name:S.function.name,arguments:S.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:S.id,name:S.function.name};let Z=J.get(S.id),H=Z?.ok??!1;H?Z?.repaired&&m.warn("RUNNER","Tool arguments repaired from non-standard JSON",{tool:S.function.name,callId:S.id}):ge.toolError(S.function.name,`Invalid JSON arguments (${Z?.reason||"parse failed"}): ${S.function.arguments.substring(0,200)}...`),yield {type:"tool_call_done",id:S.id,name:S.function.name,arguments:S.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:S.id,name:S.function.name,arguments:S.function.arguments},event_type:"response.function_call_arguments.done"};}let ie=new Set,K=null,xe=q.length>1;process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`Processing ${q.length} tool call(s)`,{isParallel:xe,tools:q.map(S=>S.function.name)});for(let S of q){let U=J.get(S.id);if(!U?.ok){let de=`Invalid JSON arguments for tool "${S.function.name}": ${U?.reason||"parse failed"}. Return strict JSON object arguments.`;yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:de,success:!1},this.memory.addToolResult(S.id,S.function.name,de),this.loopDetector.updateLastStatus("error"),ie.add(S.id);continue}let Z=U.args,H=this.loopDetector.detect(S.function.name,Z);if(this.loopDetector.record(S.function.name,Z),H===0)continue;let se=this.loopDetector.generateIntervention(H,S.function.name,Z);if(this.memory.add({role:"system",content:se.message}),H===2&&ru(S.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:se.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:se.message,success:!1},this.memory.addToolResult(S.id,S.function.name,se.message),this.loopDetector.updateLastStatus("error"),ie.add(S.id),se.shouldTerminate){K=se;break}}if(K&&(yield {type:"error",error:K.message},b=!0),b)break;let ee=ie.size>0?q.filter(S=>!ie.has(S.id)):q,fe=new Set(this.modeStrategy.filterTools(this.tools).map(S=>S.name)),ne=S=>S.replace(/["\s/>]+$/g,"").trim(),le=[];for(let S of ee){let U=ne(S.function.name);if(fe.has(U)||fe.has(S.function.name)){le.push(S);continue}let Z=`Tool "${S.function.name}" is not allowed in ${this.currentMode} mode`;ge.toolError(S.function.name,Z),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:Z,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:Z,success:!1},this.memory.addToolResult(S.id,S.function.name,Z),m.info("PERMISSION",`Tool blocked by mode: ${S.function.name} - ${Z}`);}if(le.length===0)continue;let Q=le.map(S=>({id:S.id,type:"function",function:{name:S.function.name,arguments:(()=>{let U=J.get(S.id);return U?.ok?JSON.stringify(U.args):S.function.arguments})()}})),Be=!1;if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${Q.length}`),!this.modeStrategy.shouldAutoApprove()){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se=this.tools.find(Y=>Y.name===U.function.name);if(!se){m.warn("RUNNER",`Tool not found: ${U.function.name}`);continue}let be=await Mp(s,async()=>this.permissionManager.checkPermission(se,H));if(!be.allowed){S.add(U.id);let Y=be.reason||`Tool "${U.function.name}" was denied`;ge.toolError(U.function.name,Y),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:Y,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:Y,success:!1};let Ae=JSON.stringify({type:"ephemeral",status:"error",tool:U.function.name,summary:"Tool execution denied by user",error:Y,final:!0});this.memory.addToolResult(U.id,U.function.name,Ae),m.info("PERMISSION",`Tool denied: ${U.function.name} - ${Y}`),Be=!0;}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;ge.toolError(U.function.name,Z?.message||"permission check failed");}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during permission check"),b=!0;break}throw U}if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Be){m.info("RUNNER","User denied tool - terminating current turn");break}if(Q.length===0)continue}if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${Q.length}, userDeniedTool=${Be}`),this.toolInputGuardrails.length>0){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se={tool_name:U.function.name,tool_input:H,tool_call_id:U.id},be=this.tools.find(de=>de.name===U.function.name);if(!be)continue;this.runContext.iteration=p;let Y=await Mp(s,async()=>Rs.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:se,agent_name:this.agentName,tool:be}));if(!Y.should_execute){S.add(U.id);let de=Y.rejection_message||`Tool ${U.function.name} was blocked by guardrail`;ge.toolError(U.function.name,`Blocked by guardrail: ${de}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:de,success:!1},this.memory.addToolResult(U.id,U.function.name,de),bl(this.runContext,U.function.name,H,!1);}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;if(Z instanceof yt){ge.toolError(U.function.name,`Guardrail tripwire triggered: ${Z.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${U.function.name}: ${Z.message}`},b=!0;break}ge.toolError(U.function.name,`Guardrail check failed: ${Z?.message}`);}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during guardrails check"),b=!0;break}throw U}if(b)break;if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Q.length===0)continue}process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${Q.length}`);let qe=await this.parallelExecutor.execute(Q,this.tools,S=>{if(ge.toolCall(S.name,{}),S.success){let Z=typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length;ge.toolResult(S.name,!0,Z,S.executionTime||0);}else ge.toolError(S.name,S.output);let U={type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()};},s),B=0,re=0,V=0,pe=!1;for(let S of qe.results){if(this.toolMetricsHistory.push({name:S.name,duration:S.executionTime||0,success:S.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.name,output:S.output,success:S.success},(S.name==="update_plan"||S.name==="call_tool")&&S.success)try{m.info("PLAN_UPDATE","\u{1F525} Detected plan-related tool call",{resultId:S.id,toolName:S.name,toolCallsCount:q.length});let Y=q.find(de=>de.id===S.id);if(Y){m.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:Y.id,argsLength:Y.function.arguments?.length});let de=fn(Y.function.arguments||"{}");if(!de.ok)throw new Error(de.reason||"Invalid update_plan arguments");let Ae=de.args,et=null;if(S.name==="update_plan"?et=Ae:S.name==="call_tool"&&Ae?.name==="update_plan"&&(et=Ae.args),!et||!Array.isArray(et.plan))m.debug("PLAN_UPDATE","Skip non-update_plan call_tool",{resultId:S.id,toolName:S.name,callToolName:Ae?.name});else {let An=!0;if(typeof S.output=="string")try{let gs=JSON.parse(S.output);gs&&typeof gs=="object"&&"success"in gs&&(An=gs.success!==!1);}catch{}An?(m.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!et.explanation,planSteps:et.plan?.length}),yield {type:"plan_update",explanation:et.explanation,plan:et.plan,timestamp:Date.now()},m.info("PLAN_UPDATE","\u2705 Emitted plan_update event")):m.warn("PLAN_UPDATE","Skip failed update_plan output",{resultId:S.id});}}else m.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:S.id,availableIds:q.map(de=>de.id)});}catch(Y){m.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:Y});}let Z=typeof S.output=="string"?Pp(S.output):Pp(JSON.stringify(S.output));Z=this.enrichToolResult(Z,S.name,S.executionTime||0);let H=q.find(Y=>Y.id===S.id),se={};if(H){let Y=fn(H.function.arguments||"{}");Y.ok&&(se=Y.args);}if(this.toolOutputGuardrails.length>0)try{let Y=this.tools.find(de=>de.name===S.name);if(Y){let de={tool_name:S.name,tool_input:se,tool_call_id:S.id},Ae=await Rs.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:de,agent_name:this.agentName,tool:Y,output:S.output});Ae.should_use_output||(Z=Ae.replacement_message||"[Output blocked by guardrail]",ge.toolError(S.name,"Output blocked by guardrail"));}}catch(Y){Y instanceof yt&&ge.toolError(S.name,`Output guardrail tripwire triggered: ${Y.message}`);}if(!S.success&&typeof S.output=="string"){let Y=S.output.toLowerCase();if(Y.includes("operation cancelled")||Y.includes("command interrupted")||Y.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),m.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),b=!0;break}}bl(this.runContext,S.name,se,S.success),m.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${S.name}`,{toolName:S.name,success:S.success,rawLength:typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length,truncatedLength:Z.length,outputPreview:Z.substring(0,500)}),this.memory.addToolResult(S.id,S.name,Z);let be=S.success?"success":"error";try{let Y=typeof S.output=="string"?S.output:JSON.stringify(S.output),de=JSON.parse(Y);de.status==="already_done"?be="already_done":de.status==="success"?be="success":de.status==="error"&&(be="error");}catch{}if(this.loopDetector.updateLastStatus(be),_.push({iteration:p,name:S.name,status:be,executionTime:S.executionTime||0}),_.length>24&&_.shift(),be==="error"?re++:be==="already_done"?(V++,this.isVerificationTool(S.name)&&(pe=!0)):(B++,this.isVerificationTool(S.name)&&(pe=!0)),be==="error"){let Y=(C.get(S.name)||0)+1;if(C.set(S.name,Y),S.name==="edit_file"&&(Y===2||Y===3)){let de=typeof S.output=="string"?S.output:JSON.stringify(S.output),Ae=S.name,et=Rp(Ae,de);this.memory.add({role:"system",content:et});}}else C.set(S.name,0);}if(p>0&&p%5===0){let S=this.buildPerformanceHint();S&&(this.memory.add({role:"system",content:S}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",S));}let Re=B+V>0;if(k=re>0&&!Re?k+1:0,process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Iteration quality",{iteration:p,executionTask:M,success:B,alreadyDone:V,error:re,lowProgressStreak:k,verificationSuccess:pe}),M&&k>=2&&(this.memory.add({role:"system",content:this.buildLowProgressReplanPrompt(k)}),T++,k=0,yield {type:"raw_response_event",data:{type:"loop.progress_gate",iteration:p,reason:"low_progress",nudgeCount:T},event_type:"loop.progress_gate"}),process.env.CLI_DEBUG_CONSOLE==="1"&&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: ${q.length}`),m.info("RUNNER",`Iteration: ${p}`)),this.structuredValidator){let J=this.structuredValidator.validate(N);if(J.ok)h=J.normalized||N,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:h,parsed:J.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:J.reason,message:J.message,errors:J.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(J)}),h="";continue}}else h=N;this.outputGuardrails.length>0&&h&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Rs.runOutputGuardrails(this.outputGuardrails,n,this.agentName,h),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});let z=this.evaluateCompletionEvidence(M,g,_);if(!z.ok){T++,this.memory.add({role:"system",content:this.buildEvidenceRequiredPrompt(z.reason)}),process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Completion blocked: missing evidence",{iteration:p,reason:z.reason,nudgeCount:T}),yield {type:"raw_response_event",data:{type:"loop.completion_gate",iteration:p,reason:z.reason,nudgeCount:T},event_type:"loop.completion_gate"};continue}break}}catch(O){if(O?.type==="stream_retry"){R=true,yield O;continue}let $=O instanceof Ce?O:ft(O);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:$.category,code:$.code,retryable:$.retryable,message:$.message}),$.category==="canceled"){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if($.retryable&&F<x&&!R){F++;let G=hr($.category,F,$.retryAfter),q=$.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:q,isStreamTimeout:oe,isNetworkError:ue},event_type:"runner.stream_retry"},await gn(G),p--;continue}let P=Gi($),N=$.message;P&&!N.includes(P)&&(N=`${N}
1488
1488
 
1489
1489
  \u{1F4A1} Suggestion: ${P}`),b=true;let D=kp(N,{providerName:this.providerName});ge.agentError(D),yield {type:"raw_response_event",data:{type:"error.classified",category:$.category,code:$.code,message:$.message,retryable:$.retryable,suggestion:P,context:$.context},event_type:"error.classified"},yield {type:"error",error:D};break}}!b&&!v&&p>=j&&!h&&(w=w||"iteration_limit",b=true,yield {type:"error",error:`Reached max iterations (${j}). Please summarize progress and ask whether to continue.`}),b||(ge.agentComplete(p,g,f),m.info("LLM",`Complete: iterations=${p}, toolCalls=${g}, tokens=${f.totalTokens} (prompt=${f.promptTokens}, completion=${f.completionTokens})`)),process.env.CLI_DEBUG==="1"&&(m.debug("RUNNER","=== runner.run COMPLETING ==="),m.debug("RUNNER",` iterations: ${p}`),m.debug("RUNNER",` toolCalls: ${g}`),m.debug("RUNNER",` encounteredError: ${b}`),w&&m.debug("RUNNER",` stoppedBy: ${w}`)),yield {type:"run_done"},process.env.CLI_DEBUG==="1"&&m.debug("RUNNER","=== runner.run END (run_done yielded) ===");}shouldAutoContinuePlan(e){if(!this.plannerMode)return false;let t=(e||"").trim();if(t.length<40)return false;let s=t.toLowerCase();return ["planned steps","plan:","execution plan","\u884C\u52A8\u8BA1\u5212","\u8BA1\u5212\uFF1A","\u8BA1\u5212\u5982\u4E0B","\u65B9\u6848\uFF1A","\u6B65\u9AA4\u8BA1\u5212"].some(o=>s.includes(o))?(t.match(/(^|\n)\s*[-*•]\s+/g)||[]).length+(t.match(/(^|\n)\s*\d+\.\s+/g)||[]).length>=2:false}buildPlanFollowupPrompt(){return "Plan approved. Continue executing the plan step by step and start working immediately."}isExecutionOrientedTask(e){let t=(e||"").toLowerCase();return t.trim()?/(修复|修改|实现|编写|重构|新增|删除|运行|测试|构建|验证|fix|implement|write|edit|refactor|run|test|build|validate|debug)/i.test(t):false}isVerificationTool(e){let t=(e||"").toLowerCase();return t.includes("read")||t.includes("search")||t.includes("grep")||t.includes("test")||t.includes("lint")||t.includes("build")||t.includes("check")||t.includes("execute_shell")||t==="bash"}isMutationTool(e){let t=(e||"").toLowerCase();return t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("delete")||t.includes("rename")}evaluateCompletionEvidence(e,t,s){if(this.currentMode==="auto")return {ok:true,reason:"assistant_mode"};if(!e)return {ok:true,reason:"non_execution_task"};if(t===0)return {ok:false,reason:"no_tool_execution"};let r=s.slice(-10).filter(l=>l.status==="success"||l.status==="already_done");return r.length===0?{ok:false,reason:"no_successful_tool_result"}:r.some(l=>this.isVerificationTool(l.name))?{ok:true,reason:"verified"}:r.some(l=>this.isMutationTool(l.name))?{ok:false,reason:"missing_validation_after_mutation"}:{ok:true,reason:"sufficient_success"}}buildLowProgressReplanPrompt(e){return ["[LOOP OPTIMIZER NOTICE]",`You had ${e} low-progress iterations (mostly failed tool calls).`,"Pause and re-plan before next tool call.","Required:","1) Briefly state root cause of previous failures.","2) Choose a different tool/argument strategy.","3) Run one verification step to confirm progress."].join(`
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(`
@@ -1494,20 +1494,20 @@ Available operations: All tools (auto-approved).`}shouldAutoApprove(){return tr
1494
1494
  [Performance Notice]
1495
1495
  ${n.join(`
1496
1496
  `)}
1497
- `}};W();var qv={name:"require_read_before_edit",guardrail_function:async a=>{let{tool_name:e,tool_input:t}=a.tool_context;if(e!=="edit_file")return ji();let s=t.file_path;if(!s)return ji();let n=l=>te__default.resolve(l).replace(/\\/g,"/"),r=n(s),i=Cp(a.context,20);return process.env.CLI_DEBUG==="1"&&(m.debug("GUARDRAIL",`Checking edit for: ${s}`),m.debug("GUARDRAIL",`Normalized path: ${r}`),m.debug("GUARDRAIL",`Recent tool calls (${i.length}):`),i.forEach((l,c)=>{if(l.name==="readfile"){let u=l.args.path,d=u?n(u):"undefined";m.debug("GUARDRAIL",` [${c}] readfile: ${u} (normalized: ${d}) success=${l.success}`);}})),i.some(l=>{if(l.name!=="readfile"||!l.success)return false;let c=l.args.path;if(!c)return false;let d=n(c)===r||c===s;return process.env.CLI_DEBUG==="1"&&d&&m.debug("GUARDRAIL",` \u2713 Found matching readfile: ${c}`),d})?ji():(m.warn("GUARDRAIL",`Edit without recent readfile: ${s} (abs: ${r})`),process.env.CLI_DEBUG==="1"&&m.debug("GUARDRAIL",`Available readfile calls: ${i.filter(l=>l.name==="readfile").length}`),up(`\u26A0\uFE0F \u7F16\u8F91\u524D\u8BF7\u5148\u8BFB\u53D6\u6587\u4EF6
1497
+ `}};W();var zv={name:"require_read_before_edit",guardrail_function:async a=>{let{tool_name:e,tool_input:t}=a.tool_context;if(e!=="edit_file")return ji();let s=t.file_path;if(!s)return ji();let n=l=>te__default.resolve(l).replace(/\\/g,"/"),r=n(s),i=Cp(a.context,20);return process.env.CLI_DEBUG==="1"&&(m.debug("GUARDRAIL",`Checking edit for: ${s}`),m.debug("GUARDRAIL",`Normalized path: ${r}`),m.debug("GUARDRAIL",`Recent tool calls (${i.length}):`),i.forEach((l,c)=>{if(l.name==="readfile"){let u=l.args.path,d=u?n(u):"undefined";m.debug("GUARDRAIL",` [${c}] readfile: ${u} (normalized: ${d}) success=${l.success}`);}})),i.some(l=>{if(l.name!=="readfile"||!l.success)return false;let c=l.args.path;if(!c)return false;let d=n(c)===r||c===s;return process.env.CLI_DEBUG==="1"&&d&&m.debug("GUARDRAIL",` \u2713 Found matching readfile: ${c}`),d})?ji():(m.warn("GUARDRAIL",`Edit without recent readfile: ${s} (abs: ${r})`),process.env.CLI_DEBUG==="1"&&m.debug("GUARDRAIL",`Available readfile calls: ${i.filter(l=>l.name==="readfile").length}`),up(`\u26A0\uFE0F \u7F16\u8F91\u524D\u8BF7\u5148\u8BFB\u53D6\u6587\u4EF6
1498
1498
 
1499
1499
  \u6587\u4EF6: ${s}
1500
1500
 
1501
1501
  \u{1F4A1} \u8BF7\u5148\u4F7F\u7528 readfile \u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9\uFF0C\u786E\u8BA4\u5F53\u524D\u72B6\u6001\u540E\u518D\u8FDB\u884C\u7F16\u8F91\u3002
1502
- \u8FD9\u53EF\u4EE5\u907F\u514D\u57FA\u4E8E\u8FC7\u65F6\u4FE1\u606F\u8FDB\u884C\u7F16\u8F91\u3002`,{file_path:s,suggestion:"use readfile first"}))}};var Lp=[qv],Op=[];var Lt=class{prepareRequest(e,t){let{model:s,temperature:n,maxInputTokens:r,disableSystemPrompt:i,systemPromptOverride:o,...l}=t,c=this.constraints.validateParams({model:s,temperature:n,max_tokens:r,...l}),u=this.constraints.normalizeParams({model:s,temperature:n,max_tokens:r,...l}),d=i?null:o&&o.trim().length>0?o:this.promptBuilder.buildSystemPrompt({workDir:process.cwd(),language:this.detectLanguage(),modelName:s}),p=i||!d?e:this.injectSystemPrompt(e,d),h={...u,model:s,maxInputTokens:this.applyTokenLimits(s,r)};return {messages:p,options:h,validation:{valid:c.valid,errors:c.errors,warnings:c.warnings}}}injectSystemPrompt(e,t){if(e.some(n=>n.role==="system")){let n=e.filter(o=>o.role==="system").map(o=>this.normalizeSystemContent(o.content)).filter(o=>o.length>0),r=n.length>0?[t,...n].join(`
1502
+ \u8FD9\u53EF\u4EE5\u907F\u514D\u57FA\u4E8E\u8FC7\u65F6\u4FE1\u606F\u8FDB\u884C\u7F16\u8F91\u3002`,{file_path:s,suggestion:"use readfile first"}))}};var Lp=[zv],Op=[];var Lt=class{prepareRequest(e,t){let{model:s,temperature:n,maxInputTokens:r,disableSystemPrompt:i,systemPromptOverride:o,...l}=t,c=this.constraints.validateParams({model:s,temperature:n,max_tokens:r,...l}),u=this.constraints.normalizeParams({model:s,temperature:n,max_tokens:r,...l}),d=i?null:o&&o.trim().length>0?o:this.promptBuilder.buildSystemPrompt({workDir:process.cwd(),language:this.detectLanguage(),modelName:s}),p=i||!d?e:this.injectSystemPrompt(e,d),h={...u,model:s,maxInputTokens:this.applyTokenLimits(s,r)};return {messages:p,options:h,validation:{valid:c.valid,errors:c.errors,warnings:c.warnings}}}injectSystemPrompt(e,t){if(e.some(n=>n.role==="system")){let n=e.filter(o=>o.role==="system").map(o=>this.normalizeSystemContent(o.content)).filter(o=>o.length>0),r=n.length>0?[t,...n].join(`
1503
1503
 
1504
- `):t,i=e.filter(o=>o.role!=="system");return [{role:"system",content:r},...i]}return [{role:"system",content:t},...e]}normalizeSystemContent(e){return e?typeof e=="string"?e.trim():Array.isArray(e)?e.map(s=>!s||typeof s!="object"?"":s.type==="text"&&typeof s.text=="string"?s.text:"").join("").trim():String(e).trim():""}applyTokenLimits(e,t){if(!e)return t;let s=this.constraints.getTokenLimits(e);return Math.min(t||4096,s.maxOutput)}detectLanguage(){return process.env.NEOX_LANGUAGE==="en"?"en":"zh"}};var zv={"gpt-5.2":{id:"gpt-5.2",displayName:"GPT-5.2",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:98,vision:92,creativity:94,speed:75,cost:25},releaseDate:"2025-12-11",notes:'400K \u4E0A\u4E0B\u6587\u7A97\u53E3,128K \u8F93\u51FA\u9650\u5236,\u4EE3\u53F7"Garlic"'},"gpt-5.2-codex":{id:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",provider:"openai",aliases:["gpt-5.2-codex"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:98,reasoning:97,vision:90,creativity:92,speed:70,cost:20},releaseDate:"2025-12-10",notes:"GPT-5.2 \u7684 Codex \u9ED8\u8BA4\u7248\u672C,\u4E13\u4E3A\u7F16\u7A0B\u4EFB\u52A1\u4F18\u5316"},"gpt-5.2-codex-high":{id:"gpt-5.2-codex-high",displayName:"GPT-5.2 Codex High",provider:"openai",aliases:["gpt-5.2-codex-h"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:99,reasoning:98,vision:90,creativity:93,speed:60,cost:15},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u9AD8\u6027\u80FD\u6A21\u5F0F,\u6700\u5F3A\u7F16\u7A0B\u80FD\u529B,\u66F4\u6162\u66F4\u8D35"},"gpt-5.2-codex-medium":{id:"gpt-5.2-codex-medium",displayName:"GPT-5.2 Codex Medium",provider:"openai",aliases:["gpt-5.2-codex-m"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:94,vision:88,creativity:90,speed:80,cost:40},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u5E73\u8861\u6A21\u5F0F,\u6027\u4EF7\u6BD4\u4F18\u9009"},"gpt-5.1":{id:"gpt-5.1",displayName:"GPT-5.1",provider:"openai",maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:96,vision:90,creativity:92,speed:80,cost:30},notes:"272K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA,\u9002\u5408\u957F\u4E0A\u4E0B\u6587\u4EFB\u52A1"},"gpt-5.1-codex":{id:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",provider:"openai",aliases:["gpt-5-codex","gpt-5.1-codex-max"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:97,reasoning:95,vision:88,creativity:90,speed:75,cost:25},notes:"Codex \u4F18\u5316\u7248,400K \u4E0A\u4E0B\u6587,\u4E13\u4E3A agentic \u7F16\u7A0B\u5DE5\u4F5C\u6D41\u8BBE\u8BA1"},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",displayName:"GPT-5.1 Codex Mini",provider:"openai",aliases:["gpt-5-codex-mini"],maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:85,speed:92,cost:85},notes:"\u66F4\u5FEB\u66F4\u4FBF\u5B9C\u7684 Codex \u7248\u672C"},"gpt-5":{id:"gpt-5",displayName:"GPT-5",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:94,vision:90,creativity:94,speed:80,cost:35},deprecated:true,replacedBy:"gpt-5.1",notes:"\u5DF2\u88AB GPT-5.1 \u66FF\u4EE3"},"gpt-4.1":{id:"gpt-4.1",displayName:"GPT-4.1",provider:"openai",aliases:["gpt-4.1-2025-04-14"],maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:92,vision:88,creativity:90,speed:65,cost:15},releaseDate:"2025-04-14",notes:"\u8D85\u5927 1M+ \u4E0A\u4E0B\u6587\u7A97\u53E3,\u9002\u5408\u5904\u7406\u5927\u578B\u4EE3\u7801\u5E93"},"gpt-4o":{id:"gpt-4o",displayName:"GPT-4o",provider:"openai",aliases:["gpt-4o-2024-11-20","gpt-4o-2024-08-06"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:85,vision:88,creativity:88,speed:75,cost:50}},"gpt-4o-mini":{id:"gpt-4o-mini",displayName:"GPT-4o Mini",provider:"openai",aliases:["gpt-4o-mini-2024-07-18"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:80,creativity:75,speed:92,cost:90}},o3:{id:"o3",displayName:"o3",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:99,vision:0,creativity:78,speed:40,cost:15},notes:"\u65B0\u4E00\u4EE3\u63A8\u7406\u6A21\u578B,\u63A8\u7406\u80FD\u529B\u6700\u5F3A"},"o3-mini":{id:"o3-mini",displayName:"o3 Mini",provider:"openai",aliases:["o3-mini-2025-01-31"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:65,cost:60}},"o4-mini":{id:"o4-mini",displayName:"o4 Mini",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:96,vision:0,creativity:76,speed:70,cost:55}},o1:{id:"o1",displayName:"o1",provider:"openai",aliases:["o1-2024-12-17"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:45,cost:25}},"o1-mini":{id:"o1-mini",displayName:"o1 Mini",provider:"openai",aliases:["o1-mini-2024-09-12"],maxInputTokens:128e3,maxOutputTokens:65536,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:82,reasoning:88,vision:0,creativity:70,speed:70,cost:70}},"codex-mini-latest":{id:"codex-mini-latest",displayName:"Codex Mini (Latest)",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:88,cost:80}},"gpt-4-turbo":{id:"gpt-4-turbo",displayName:"GPT-4 Turbo",provider:"openai",aliases:["gpt-4-turbo-2024-04-09"],maxInputTokens:128e3,maxOutputTokens:4096,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:87,vision:85,creativity:90,speed:70,cost:40}},"gpt-3.5-turbo":{id:"gpt-3.5-turbo",displayName:"GPT-3.5 Turbo",provider:"openai",maxInputTokens:16385,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:65,reasoning:60,vision:0,creativity:70,speed:95,cost:98}}},Hv={"claude-opus-4-6":{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",provider:"anthropic",aliases:["claude-opus-4.6"],maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:99,reasoning:98,vision:91,creativity:96,speed:66,cost:18},notes:"Claude Opus 4.6 (latest alias)"},"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",provider:"anthropic",aliases:["claude-opus-4.5"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:98,reasoning:97,vision:90,creativity:95,speed:65,cost:20},releaseDate:"2025-11-24",notes:"\u6700\u5F3A Claude \u6A21\u578B,\u652F\u6301 Extended Thinking,\u4F01\u4E1A\u7248\u53EF\u6269\u5C55\u81F3 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",provider:"anthropic",aliases:["claude-sonnet-4.5","claude-sonnet-4-5-20250929-thinking"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:88,creativity:90,speed:80,cost:50},releaseDate:"2025-09-29",notes:"\u5E73\u8861\u6027\u80FD\u4E0E\u6210\u672C,beta \u7248\u672C\u652F\u6301 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-20250514":{id:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",provider:"anthropic",aliases:["claude-sonnet-4"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:88,speed:82,cost:55},notes:"2025-08-12 \u5347\u7EA7\u652F\u6301 1M beta \u4E0A\u4E0B\u6587"},"claude-opus-4-20250514":{id:"claude-opus-4-20250514",displayName:"Claude Opus 4",provider:"anthropic",aliases:["claude-opus-4"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:95,vision:88,creativity:94,speed:70,cost:25}},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",provider:"anthropic",aliases:["claude-haiku-4.5"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:78,reasoning:75,vision:80,creativity:75,speed:95,cost:95},notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 4.5 \u6A21\u578B"},"claude-3-5-sonnet-20241022":{id:"claude-3-5-sonnet-20241022",displayName:"Claude 3.5 Sonnet (New)",provider:"anthropic",aliases:["claude-3.5-sonnet-new","claude-3-5-sonnet-latest"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:85,cost:55},releaseDate:"2024-10-22",notes:"Claude 3.5 Sonnet \u5347\u7EA7\u7248"},"claude-3-5-haiku-20241022":{id:"claude-3-5-haiku-20241022",displayName:"Claude 3.5 Haiku",provider:"anthropic",aliases:["claude-3.5-haiku"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:78,creativity:73,speed:98,cost:98},releaseDate:"2024-10-22",notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 3.5 \u6A21\u578B"}},Jv={"gemini-3-pro-preview":{id:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",provider:"gemini",aliases:["gemini-3-pro","gemini-3.0-pro-preview"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:95,vision:96,creativity:94,speed:72,cost:35},releaseDate:"2026-01",notes:"Gemini 3 \u9884\u89C8\u7248,UI/\u89C6\u89C9\u8BBE\u8BA1\u4E13\u957F,1M \u4E0A\u4E0B\u6587"},"gemini-3.0-pro":{id:"gemini-3.0-pro",displayName:"Gemini 3.0 Pro",provider:"gemini",aliases:["gemini-3.0-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:96,vision:94,creativity:92,speed:70,cost:30},releaseDate:"2025-12",notes:"Flagship multimodal model with 1M context, high-precision reasoning"},"gemini-2.5-flash":{id:"gemini-2.5-flash",displayName:"Gemini 2.5 Flash",provider:"gemini",aliases:["gemini-2.5-flash-latest"],maxInputTokens:1048576,maxOutputTokens:65535,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:90,creativity:87,speed:92,cost:85},releaseDate:"2025-03",notes:"Fast and cost-efficient, ~1500 pages or 30K lines of code"},"gemini-2.5-pro":{id:"gemini-2.5-pro",displayName:"Gemini 2.5 Pro",provider:"gemini",aliases:["gemini-2.5-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:92,vision:92,creativity:90,speed:75,cost:40},releaseDate:"2025-03",notes:"Balanced performance with 1M context window"},"gemini-2.0-flash-thinking":{id:"gemini-2.0-flash-thinking",displayName:"Gemini 2.0 Flash Thinking",provider:"gemini",aliases:["gemini-2.0-flash-thinking-exp","gemini-2.0-flash-thinking-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:94,vision:90,creativity:88,speed:85,cost:50},releaseDate:"2024-12-19",notes:"Shows model thought process, 1M context window"},"gemini-2.0-flash":{id:"gemini-2.0-flash",displayName:"Gemini 2.0 Flash",provider:"gemini",aliases:["gemini-2.0-flash-exp","gemini-2.0-flash-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:89,vision:90,creativity:87,speed:95,cost:75},releaseDate:"2024-12-11",notes:"Twice as fast as Gemini 1.5 Pro, multimodal with native image generation"},"gemini-1.5-pro":{id:"gemini-1.5-pro",displayName:"Gemini 1.5 Pro",provider:"gemini",aliases:["gemini-1.5-pro-latest","gemini-pro"],maxInputTokens:2e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:87,vision:88,creativity:85,speed:70,cost:50},releaseDate:"2024-05",notes:"2M context window - largest available, supports context caching"},"gemini-1.5-flash":{id:"gemini-1.5-flash",displayName:"Gemini 1.5 Flash",provider:"gemini",aliases:["gemini-1.5-flash-latest","gemini-flash"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:83,vision:85,creativity:82,speed:90,cost:85},releaseDate:"2024-05",notes:"Fast and efficient with 1M context, supports code execution"},"gemini-1.5-flash-8b":{id:"gemini-1.5-flash-8b",displayName:"Gemini 1.5 Flash-8B",provider:"gemini",aliases:["gemini-flash-8b"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:82,creativity:77,speed:98,cost:95},releaseDate:"2024-10",notes:"Smaller 8B model, extremely fast and cost-effective"},"gemini-1.0-pro":{id:"gemini-1.0-pro",displayName:"Gemini 1.0 Pro",provider:"gemini",aliases:["gemini-pro-1.0"],maxInputTokens:32768,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:73,vision:0,creativity:75,speed:85,cost:90},releaseDate:"2023-12",notes:"Original Gemini Pro, text-only"},"gemini-1.0-pro-vision":{id:"gemini-1.0-pro-vision",displayName:"Gemini 1.0 Pro Vision",provider:"gemini",aliases:["gemini-pro-vision"],maxInputTokens:16384,maxOutputTokens:2048,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:80,creativity:72,speed:80,cost:88},releaseDate:"2023-12",notes:"Original multimodal Gemini with vision support"}},Kv={"kimi-k2-0905-preview":{id:"kimi-k2-0905-preview",displayName:"Kimi K2 (0905 Preview)",provider:"kimi",aliases:["kimi-k2","kimi-k2-preview"],maxInputTokens:256e3,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:70},releaseDate:"2025-09",notes:"MoE \u67B6\u6784 K2 \u9884\u89C8\u7248\uFF0C256K \u4E0A\u4E0B\u6587"}},Vv={"deepseek-v3.2":{id:"deepseek-v3.2",displayName:"DeepSeek V3.2",provider:"deepseek",aliases:["deepseek-v3.2-exp"],maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:95},releaseDate:"2025-09-29",notes:"\u5B9E\u9A8C\u7248\u672C,\u6027\u80FD\u663E\u8457\u63D0\u5347"},"deepseek-v3.1":{id:"deepseek-v3.1",displayName:"DeepSeek V3.1",provider:"deepseek",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:78,speed:88,cost:96},releaseDate:"2025-08",notes:"\u6DF7\u5408\u67B6\u6784\u6A21\u578B"},"deepseek-chat":{id:"deepseek-chat",displayName:"DeepSeek Chat",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:85,cost:95},notes:"\u901A\u7528\u5BF9\u8BDD\u6A21\u578B,\u6210\u672C\u6781\u4F4E"},"deepseek-coder":{id:"deepseek-coder",displayName:"DeepSeek Coder",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:85,vision:0,creativity:70,speed:88,cost:96},notes:"\u4E13\u4E3A\u7F16\u7A0B\u4F18\u5316,\u4EE3\u7801\u80FD\u529B\u7A81\u51FA"},"deepseek-reasoner":{id:"deepseek-reasoner",displayName:"DeepSeek Reasoner",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:96,vision:0,creativity:75,speed:60,cost:90},notes:"\u63A8\u7406\u4E13\u7528\u6A21\u578B,\u652F\u6301\u957F\u8F93\u51FA"}},Yv={"minimax-text-01":{id:"minimax-text-01",displayName:"MiniMax Text-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:90,vision:0,creativity:85,speed:55,cost:70},notes:"4M \u4E0A\u4E0B\u6587\u7A97\u53E3,Lightning Attention + MoE \u67B6\u6784,\u5F00\u6E90\u53EF\u7528"},"minimax-m1-80k":{id:"minimax-m1-80k",displayName:"MiniMax M1-80K",provider:"minimax",maxInputTokens:1e6,maxOutputTokens:8e4,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:92,vision:0,creativity:82,speed:65,cost:75},notes:"1M \u4E0A\u4E0B\u6587 + 80K \u601D\u8003\u9884\u7B97"},"minimax-m2.1":{id:"minimax-m2.1",displayName:"MiniMax M2.1",provider:"minimax",maxInputTokens:2e5,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:88,vision:0,creativity:80,speed:82,cost:85},releaseDate:"2025-12",notes:"\u7F16\u7A0B\u548C Agentic \u5DE5\u4F5C\u6D41\u4F18\u5316,\u652F\u6301\u591A\u8BED\u8A00"},"minimax-vl-01":{id:"minimax-vl-01",displayName:"MiniMax VL-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:92,creativity:88,speed:60,cost:65},notes:"\u591A\u6A21\u6001\u6A21\u578B,\u652F\u6301\u6587\u672C\u548C\u56FE\u50CF"}},Xv={"glm-4.7":{id:"glm-4.7",displayName:"GLM-4.7",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:80,cost:70},releaseDate:"2025-12-22",notes:"\u6700\u65B0\u7248\u672C,200K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA"},"glm-4.6":{id:"glm-4.6",displayName:"GLM-4.6",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:83,creativity:85,speed:82,cost:75},releaseDate:"2025-09-10",notes:"\u4ECE 128K \u6269\u5C55\u81F3 200K \u4E0A\u4E0B\u6587"},"glm-4.5":{id:"glm-4.5",displayName:"GLM-4.5",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:86,reasoning:84,vision:80,creativity:83,speed:85,cost:80},releaseDate:"2025-07"},"glm-4-flash":{id:"glm-4-flash",displayName:"GLM-4 Flash",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:82,reasoning:80,vision:78,creativity:80,speed:95,cost:92},notes:"\u5FEB\u901F\u6A21\u578B,\u76F8\u5F53\u4E8E 300 \u9875\u4E66\u7684\u4E0A\u4E0B\u6587"},"glm-4-plus":{id:"glm-4-plus",displayName:"GLM-4 Plus",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:82,creativity:85,speed:78,cost:65}},"glm-4-air":{id:"glm-4-air",displayName:"GLM-4 Air",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:0,creativity:78,speed:90,cost:88}},"glm-4-long":{id:"glm-4-long",displayName:"GLM-4 Long",provider:"glm",maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:0,creativity:80,speed:50,cost:60},notes:"\u8D85\u957F\u4E0A\u4E0B\u6587\u4E13\u7528,1M tokens"},"glm-4-airx":{id:"glm-4-airx",displayName:"GLM-4 AirX",provider:"glm",maxInputTokens:8e3,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:0,creativity:70,speed:98,cost:98},notes:"\u8D85\u8F7B\u91CF\u7EA7\u6A21\u578B,\u6781\u5FEB\u901F\u5EA6"}},Al=class{models=new Map;constructor(){this.registerModels(zv),this.registerModels(Hv),this.registerModels(Jv),this.registerModels(Kv),this.registerModels(Vv),this.registerModels(Yv),this.registerModels(Xv);}registerModels(e){for(let[t,s]of Object.entries(e))if(this.models.set(t,s),s.aliases)for(let n of s.aliases)this.models.set(n,s);}getModel(e){return this.models.get(e)}getAllModels(){let e=new Map;for(let t of this.models.values())e.set(t.id,t);return Array.from(e.values())}getModelsByProvider(e){return this.getAllModels().filter(t=>t.provider===e)}hasModel(e){return this.models.has(e)}toModelCapability(e){let t=this.getModel(e);if(t)return {modelAlias:t.id,strengths:this.inferStrengths(t),scores:{coding:t.scores?.coding??50,reasoning:t.scores?.reasoning??50,vision:t.scores?.vision??0,creativity:t.scores?.creativity??50,speed:t.scores?.speed??50,cost:t.scores?.cost??50},features:{supportsVision:t.supportsVision??false,supportsTools:t.supportsTools??false,supportsFunctionCalling:t.supportsFunctionCalling??false,supportsStreaming:t.supportsStreaming??false,maxContextTokens:t.maxInputTokens,maxOutputTokens:t.maxOutputTokens}}}inferStrengths(e){let t=[],s=e.scores??{};return (s.coding??0)>=85&&t.push("coding"),(s.reasoning??0)>=85&&t.push("reasoning"),(s.vision??0)>=85&&t.push("image_analysis"),(s.creativity??0)>=85&&t.push("creative_writing"),t}},Yi=new Al;var us=class{validateParams(e){let t=this.getConstraints(),s=[],n=[];for(let r of Object.keys(e))t.supportedParams.has(r)||n.push(`Parameter '${r}' is not supported by this provider and will be ignored`);if(t.validators){for(let[r,i]of Object.entries(t.validators))if(e[r]!==void 0){let o=i(e[r],e);o===false?s.push(`Invalid value for parameter '${r}': ${e[r]}`):typeof o=="string"&&s.push(`Parameter '${r}': ${o}`);}}if(e.model&&e.max_tokens!==void 0){let r=this.getTokenLimits(e.model);r.found&&e.max_tokens>r.maxInput?s.push(`max_tokens (${e.max_tokens}) exceeds model context window (${r.maxInput}) for ${e.model}`):r.found&&e.max_tokens>r.maxOutput&&n.push(`max_tokens (${e.max_tokens}) exceeds recommended output limit (${r.maxOutput}) for ${e.model}, but is within context window`);}return {valid:s.length===0,errors:s,warnings:n.length>0?n:void 0}}getTokenLimits(e){let t=Yi.getModel(e);if(t)return {maxOutput:t.maxOutputTokens,maxInput:t.maxInputTokens,found:true,source:"model"};let s=this.getConstraints(),n=s.maxOutputTokens[e],r=s.maxInputTokens[e];if(n!==void 0&&r!==void 0)return {maxOutput:n,maxInput:r,found:true,source:"model"};for(let[i,o]of Object.entries(s.maxOutputTokens))if(this.matchPattern(e,i))return {maxOutput:o,maxInput:s.maxInputTokens[i]||128e3,found:true,source:"model"};return {maxOutput:4096,maxInput:128e3,found:false,source:"fallback"}}normalizeParams(e){let t=this.getConstraints(),s={};for(let[n,r]of Object.entries(e)){let i=t.paramAliases?.[n]||n;t.supportedParams.has(n)&&(s[i]=r);}if(t.defaults)for(let[n,r]of Object.entries(t.defaults))s[n]===void 0&&(s[n]=r);return s}matchPattern(e,t){return t.includes("*")?new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e):e===t}isParamSupported(e){return this.getConstraints().supportedParams.has(e)}getParamAlias(e){return this.getConstraints().paramAliases?.[e]||e}};function Ve(a,e){return t=>{let s=Number(t);return isNaN(s)?"Must be a number":s<a||s>e?`Must be between ${a} and ${e}`:true}}function yn(a){return e=>a.includes(e)?true:`Must be one of: ${a.join(", ")}`}function Np(a){return e=>{let t=typeof e;return t!==a?`Expected ${a}, got ${t}`:true}}function Xi(...a){return (e,t)=>{for(let s of a){let n=s(e,t);if(n!==true)return n}return true}}var Is=class extends us{getConstraints(){return {maxOutputTokens:{"gpt-4o":16384,"gpt-4o-2024-11-20":16384,"gpt-4o-2024-08-06":16384,"gpt-4o-2024-05-13":4096,"gpt-4o-mini":16384,"gpt-4o-mini-2024-07-18":16384,"gpt-4-turbo":4096,"gpt-4-turbo-2024-04-09":4096,"gpt-4-turbo-preview":4096,"gpt-4-0125-preview":4096,"gpt-4-1106-preview":4096,"gpt-4":8192,"gpt-4-0613":8192,"gpt-4-0314":8192,"gpt-3.5-turbo":4096,"gpt-3.5-turbo-0125":4096,"gpt-3.5-turbo-1106":4096,o1:1e5,"o1-2024-12-17":1e5,"o1-preview":32768,"o1-preview-2024-09-12":32768,"o1-mini":65536,"o1-mini-2024-09-12":65536,o3:1e5,"o3-mini":1e5,"o3-mini-2025-01-31":1e5,"o4-mini":1e5,"gpt-5":1e5,"gpt-5.1":1e5,"gpt-5.1-codex":1e5,"gpt-5.1-codex-max":1e5,"gpt-5.1-codex-mini":1e5,"gpt-5.2":1e5,"gpt-5.2-codex":1e5,"gpt-5-codex":1e5,"gpt-5-codex-mini":1e5,"codex-mini-latest":1e5,"gpt-4.1":1e5,"gpt-4.1-2025-04-14":1e5,"gpt-4o*":16384,"gpt-4-turbo*":4096,"gpt-4.1*":1e5,"gpt-4*":8192,"gpt-3.5*":4096,"gpt-5*":1e5,"codex*":1e5,"o1*":1e5,"o3*":1e5,"o4*":1e5},maxInputTokens:{"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4-turbo":128e3,"gpt-4-turbo-2024-04-09":128e3,"gpt-4.1":1047576,"gpt-4.1-2025-04-14":1047576,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,"gpt-5":272e3,"gpt-5.1":272e3,"gpt-5.1-codex":272e3,"gpt-5.1-codex-max":272e3,"gpt-5.1-codex-mini":272e3,"gpt-5-codex":272e3,"gpt-5-codex-mini":272e3,"gpt-5.2":4e5,"gpt-5.2-codex":4e5,"codex-mini-latest":2e5,o1:2e5,"o1-preview":128e3,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"gpt-4o*":128e3,"gpt-4-turbo*":128e3,"gpt-4.1*":1047576,"gpt-5*":272e3,"gpt-5.2*":4e5,"codex*":272e3,"o1*":2e5,"o3*":2e5,"o4*":2e5},supportedParams:new Set(["model","messages","stream","stream_options","max_tokens","max_completion_tokens","temperature","top_p","top_k","frequency_penalty","presence_penalty","stop","n","seed","reasoning_effort","verbosity","tools","tool_choice","parallel_tool_calls","response_format","logprobs","top_logprobs","logit_bias","modalities","audio","user","safety_identifier","store","service_tier","prompt_cache_key","prompt_cache_retention","metadata","prediction","extra_body","search_parameters","web_search_options"]),validators:{temperature:Ve(0,2),top_p:Ve(0,1),frequency_penalty:Ve(-2,2),presence_penalty:Ve(-2,2),reasoning_effort:yn(["low","medium","high"]),verbosity:yn(["low","medium","high"]),tool_choice:e=>typeof e=="string"?["none","auto","required"].includes(e)||"Must be 'none', 'auto', or 'required'":typeof e=="object"&&e.type==="function"?true:"Invalid tool_choice format","response_format.type":yn(["text","json_object","json_schema"]),stream:e=>typeof e=="boolean"||"Must be a boolean",n:Xi(e=>typeof e=="number"||"Must be a number",Ve(1,10)),max_tokens:(e,t)=>{let s=Number(e);if(isNaN(s))return "Must be a number";if(s<1)return "Must be at least 1";t?.model||"";return true}},defaults:{temperature:1,top_p:1,n:1,stream:false,max_tokens:4096}}}isResponsesAPIModel(e){return e.startsWith("o1")||e.startsWith("o3")}supportsReasoning(e){return this.isResponsesAPIModel(e)}supportsVision(e){return e.includes("gpt-4o")||e.includes("gpt-4-turbo")||e.includes("gpt-4-vision")}supportsTools(e){return e.startsWith("o1-preview")||e.startsWith("o1-mini")?false:e.includes("gpt-4")||e.includes("gpt-3.5-turbo")||e.startsWith("o3")}getRecommendedMaxTokens(e,t){let s=this.getTokenLimits(e);switch(t){case "short":return Math.min(1024,s.maxOutput);case "medium":return Math.min(4096,s.maxOutput);case "long":return s.maxOutput;default:return Math.min(4096,s.maxOutput)}}};var ds=class{combinePromptSections(e){return e.filter(s=>s.content.trim().length>0).sort((s,n)=>(s.order||0)-(n.order||0)).map(s=>s.title?`# ${s.title}
1504
+ `):t,i=e.filter(o=>o.role!=="system");return [{role:"system",content:r},...i]}return [{role:"system",content:t},...e]}normalizeSystemContent(e){return e?typeof e=="string"?e.trim():Array.isArray(e)?e.map(s=>!s||typeof s!="object"?"":s.type==="text"&&typeof s.text=="string"?s.text:"").join("").trim():String(e).trim():""}applyTokenLimits(e,t){if(!e)return t;let s=this.constraints.getTokenLimits(e);return Math.min(t||4096,s.maxOutput)}detectLanguage(){return process.env.NEOX_LANGUAGE==="en"?"en":"zh"}};var Hv={"gpt-5.2":{id:"gpt-5.2",displayName:"GPT-5.2",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:98,vision:92,creativity:94,speed:75,cost:25},releaseDate:"2025-12-11",notes:'400K \u4E0A\u4E0B\u6587\u7A97\u53E3,128K \u8F93\u51FA\u9650\u5236,\u4EE3\u53F7"Garlic"'},"gpt-5.2-codex":{id:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",provider:"openai",aliases:["gpt-5.2-codex"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:98,reasoning:97,vision:90,creativity:92,speed:70,cost:20},releaseDate:"2025-12-10",notes:"GPT-5.2 \u7684 Codex \u9ED8\u8BA4\u7248\u672C,\u4E13\u4E3A\u7F16\u7A0B\u4EFB\u52A1\u4F18\u5316"},"gpt-5.2-codex-high":{id:"gpt-5.2-codex-high",displayName:"GPT-5.2 Codex High",provider:"openai",aliases:["gpt-5.2-codex-h"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:99,reasoning:98,vision:90,creativity:93,speed:60,cost:15},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u9AD8\u6027\u80FD\u6A21\u5F0F,\u6700\u5F3A\u7F16\u7A0B\u80FD\u529B,\u66F4\u6162\u66F4\u8D35"},"gpt-5.2-codex-medium":{id:"gpt-5.2-codex-medium",displayName:"GPT-5.2 Codex Medium",provider:"openai",aliases:["gpt-5.2-codex-m"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:94,vision:88,creativity:90,speed:80,cost:40},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u5E73\u8861\u6A21\u5F0F,\u6027\u4EF7\u6BD4\u4F18\u9009"},"gpt-5.1":{id:"gpt-5.1",displayName:"GPT-5.1",provider:"openai",maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:96,vision:90,creativity:92,speed:80,cost:30},notes:"272K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA,\u9002\u5408\u957F\u4E0A\u4E0B\u6587\u4EFB\u52A1"},"gpt-5.1-codex":{id:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",provider:"openai",aliases:["gpt-5-codex","gpt-5.1-codex-max"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:97,reasoning:95,vision:88,creativity:90,speed:75,cost:25},notes:"Codex \u4F18\u5316\u7248,400K \u4E0A\u4E0B\u6587,\u4E13\u4E3A agentic \u7F16\u7A0B\u5DE5\u4F5C\u6D41\u8BBE\u8BA1"},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",displayName:"GPT-5.1 Codex Mini",provider:"openai",aliases:["gpt-5-codex-mini"],maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:85,speed:92,cost:85},notes:"\u66F4\u5FEB\u66F4\u4FBF\u5B9C\u7684 Codex \u7248\u672C"},"gpt-5":{id:"gpt-5",displayName:"GPT-5",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:94,vision:90,creativity:94,speed:80,cost:35},deprecated:true,replacedBy:"gpt-5.1",notes:"\u5DF2\u88AB GPT-5.1 \u66FF\u4EE3"},"gpt-4.1":{id:"gpt-4.1",displayName:"GPT-4.1",provider:"openai",aliases:["gpt-4.1-2025-04-14"],maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:92,vision:88,creativity:90,speed:65,cost:15},releaseDate:"2025-04-14",notes:"\u8D85\u5927 1M+ \u4E0A\u4E0B\u6587\u7A97\u53E3,\u9002\u5408\u5904\u7406\u5927\u578B\u4EE3\u7801\u5E93"},"gpt-4o":{id:"gpt-4o",displayName:"GPT-4o",provider:"openai",aliases:["gpt-4o-2024-11-20","gpt-4o-2024-08-06"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:85,vision:88,creativity:88,speed:75,cost:50}},"gpt-4o-mini":{id:"gpt-4o-mini",displayName:"GPT-4o Mini",provider:"openai",aliases:["gpt-4o-mini-2024-07-18"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:80,creativity:75,speed:92,cost:90}},o3:{id:"o3",displayName:"o3",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:99,vision:0,creativity:78,speed:40,cost:15},notes:"\u65B0\u4E00\u4EE3\u63A8\u7406\u6A21\u578B,\u63A8\u7406\u80FD\u529B\u6700\u5F3A"},"o3-mini":{id:"o3-mini",displayName:"o3 Mini",provider:"openai",aliases:["o3-mini-2025-01-31"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:65,cost:60}},"o4-mini":{id:"o4-mini",displayName:"o4 Mini",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:96,vision:0,creativity:76,speed:70,cost:55}},o1:{id:"o1",displayName:"o1",provider:"openai",aliases:["o1-2024-12-17"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:45,cost:25}},"o1-mini":{id:"o1-mini",displayName:"o1 Mini",provider:"openai",aliases:["o1-mini-2024-09-12"],maxInputTokens:128e3,maxOutputTokens:65536,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:82,reasoning:88,vision:0,creativity:70,speed:70,cost:70}},"codex-mini-latest":{id:"codex-mini-latest",displayName:"Codex Mini (Latest)",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:88,cost:80}},"gpt-4-turbo":{id:"gpt-4-turbo",displayName:"GPT-4 Turbo",provider:"openai",aliases:["gpt-4-turbo-2024-04-09"],maxInputTokens:128e3,maxOutputTokens:4096,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:87,vision:85,creativity:90,speed:70,cost:40}},"gpt-3.5-turbo":{id:"gpt-3.5-turbo",displayName:"GPT-3.5 Turbo",provider:"openai",maxInputTokens:16385,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:65,reasoning:60,vision:0,creativity:70,speed:95,cost:98}}},Jv={"claude-opus-4-6":{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",provider:"anthropic",aliases:["claude-opus-4.6"],maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:99,reasoning:98,vision:91,creativity:96,speed:66,cost:18},notes:"Claude Opus 4.6 (latest alias)"},"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",provider:"anthropic",aliases:["claude-opus-4.5"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:98,reasoning:97,vision:90,creativity:95,speed:65,cost:20},releaseDate:"2025-11-24",notes:"\u6700\u5F3A Claude \u6A21\u578B,\u652F\u6301 Extended Thinking,\u4F01\u4E1A\u7248\u53EF\u6269\u5C55\u81F3 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",provider:"anthropic",aliases:["claude-sonnet-4.5","claude-sonnet-4-5-20250929-thinking"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:88,creativity:90,speed:80,cost:50},releaseDate:"2025-09-29",notes:"\u5E73\u8861\u6027\u80FD\u4E0E\u6210\u672C,beta \u7248\u672C\u652F\u6301 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-20250514":{id:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",provider:"anthropic",aliases:["claude-sonnet-4"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:88,speed:82,cost:55},notes:"2025-08-12 \u5347\u7EA7\u652F\u6301 1M beta \u4E0A\u4E0B\u6587"},"claude-opus-4-20250514":{id:"claude-opus-4-20250514",displayName:"Claude Opus 4",provider:"anthropic",aliases:["claude-opus-4"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:95,vision:88,creativity:94,speed:70,cost:25}},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",provider:"anthropic",aliases:["claude-haiku-4.5"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:78,reasoning:75,vision:80,creativity:75,speed:95,cost:95},notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 4.5 \u6A21\u578B"},"claude-3-5-sonnet-20241022":{id:"claude-3-5-sonnet-20241022",displayName:"Claude 3.5 Sonnet (New)",provider:"anthropic",aliases:["claude-3.5-sonnet-new","claude-3-5-sonnet-latest"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:85,cost:55},releaseDate:"2024-10-22",notes:"Claude 3.5 Sonnet \u5347\u7EA7\u7248"},"claude-3-5-haiku-20241022":{id:"claude-3-5-haiku-20241022",displayName:"Claude 3.5 Haiku",provider:"anthropic",aliases:["claude-3.5-haiku"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:78,creativity:73,speed:98,cost:98},releaseDate:"2024-10-22",notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 3.5 \u6A21\u578B"}},Kv={"gemini-3-pro-preview":{id:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",provider:"gemini",aliases:["gemini-3-pro","gemini-3.0-pro-preview"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:95,vision:96,creativity:94,speed:72,cost:35},releaseDate:"2026-01",notes:"Gemini 3 \u9884\u89C8\u7248,UI/\u89C6\u89C9\u8BBE\u8BA1\u4E13\u957F,1M \u4E0A\u4E0B\u6587"},"gemini-3.0-pro":{id:"gemini-3.0-pro",displayName:"Gemini 3.0 Pro",provider:"gemini",aliases:["gemini-3.0-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:96,vision:94,creativity:92,speed:70,cost:30},releaseDate:"2025-12",notes:"Flagship multimodal model with 1M context, high-precision reasoning"},"gemini-2.5-flash":{id:"gemini-2.5-flash",displayName:"Gemini 2.5 Flash",provider:"gemini",aliases:["gemini-2.5-flash-latest"],maxInputTokens:1048576,maxOutputTokens:65535,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:90,creativity:87,speed:92,cost:85},releaseDate:"2025-03",notes:"Fast and cost-efficient, ~1500 pages or 30K lines of code"},"gemini-2.5-pro":{id:"gemini-2.5-pro",displayName:"Gemini 2.5 Pro",provider:"gemini",aliases:["gemini-2.5-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:92,vision:92,creativity:90,speed:75,cost:40},releaseDate:"2025-03",notes:"Balanced performance with 1M context window"},"gemini-2.0-flash-thinking":{id:"gemini-2.0-flash-thinking",displayName:"Gemini 2.0 Flash Thinking",provider:"gemini",aliases:["gemini-2.0-flash-thinking-exp","gemini-2.0-flash-thinking-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:94,vision:90,creativity:88,speed:85,cost:50},releaseDate:"2024-12-19",notes:"Shows model thought process, 1M context window"},"gemini-2.0-flash":{id:"gemini-2.0-flash",displayName:"Gemini 2.0 Flash",provider:"gemini",aliases:["gemini-2.0-flash-exp","gemini-2.0-flash-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:89,vision:90,creativity:87,speed:95,cost:75},releaseDate:"2024-12-11",notes:"Twice as fast as Gemini 1.5 Pro, multimodal with native image generation"},"gemini-1.5-pro":{id:"gemini-1.5-pro",displayName:"Gemini 1.5 Pro",provider:"gemini",aliases:["gemini-1.5-pro-latest","gemini-pro"],maxInputTokens:2e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:87,vision:88,creativity:85,speed:70,cost:50},releaseDate:"2024-05",notes:"2M context window - largest available, supports context caching"},"gemini-1.5-flash":{id:"gemini-1.5-flash",displayName:"Gemini 1.5 Flash",provider:"gemini",aliases:["gemini-1.5-flash-latest","gemini-flash"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:83,vision:85,creativity:82,speed:90,cost:85},releaseDate:"2024-05",notes:"Fast and efficient with 1M context, supports code execution"},"gemini-1.5-flash-8b":{id:"gemini-1.5-flash-8b",displayName:"Gemini 1.5 Flash-8B",provider:"gemini",aliases:["gemini-flash-8b"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:82,creativity:77,speed:98,cost:95},releaseDate:"2024-10",notes:"Smaller 8B model, extremely fast and cost-effective"},"gemini-1.0-pro":{id:"gemini-1.0-pro",displayName:"Gemini 1.0 Pro",provider:"gemini",aliases:["gemini-pro-1.0"],maxInputTokens:32768,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:73,vision:0,creativity:75,speed:85,cost:90},releaseDate:"2023-12",notes:"Original Gemini Pro, text-only"},"gemini-1.0-pro-vision":{id:"gemini-1.0-pro-vision",displayName:"Gemini 1.0 Pro Vision",provider:"gemini",aliases:["gemini-pro-vision"],maxInputTokens:16384,maxOutputTokens:2048,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:80,creativity:72,speed:80,cost:88},releaseDate:"2023-12",notes:"Original multimodal Gemini with vision support"}},Vv={"kimi-k2-0905-preview":{id:"kimi-k2-0905-preview",displayName:"Kimi K2 (0905 Preview)",provider:"kimi",aliases:["kimi-k2","kimi-k2-preview"],maxInputTokens:256e3,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:70},releaseDate:"2025-09",notes:"MoE \u67B6\u6784 K2 \u9884\u89C8\u7248\uFF0C256K \u4E0A\u4E0B\u6587"}},Yv={"deepseek-v3.2":{id:"deepseek-v3.2",displayName:"DeepSeek V3.2",provider:"deepseek",aliases:["deepseek-v3.2-exp"],maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:95},releaseDate:"2025-09-29",notes:"\u5B9E\u9A8C\u7248\u672C,\u6027\u80FD\u663E\u8457\u63D0\u5347"},"deepseek-v3.1":{id:"deepseek-v3.1",displayName:"DeepSeek V3.1",provider:"deepseek",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:78,speed:88,cost:96},releaseDate:"2025-08",notes:"\u6DF7\u5408\u67B6\u6784\u6A21\u578B"},"deepseek-chat":{id:"deepseek-chat",displayName:"DeepSeek Chat",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:85,cost:95},notes:"\u901A\u7528\u5BF9\u8BDD\u6A21\u578B,\u6210\u672C\u6781\u4F4E"},"deepseek-coder":{id:"deepseek-coder",displayName:"DeepSeek Coder",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:85,vision:0,creativity:70,speed:88,cost:96},notes:"\u4E13\u4E3A\u7F16\u7A0B\u4F18\u5316,\u4EE3\u7801\u80FD\u529B\u7A81\u51FA"},"deepseek-reasoner":{id:"deepseek-reasoner",displayName:"DeepSeek Reasoner",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:96,vision:0,creativity:75,speed:60,cost:90},notes:"\u63A8\u7406\u4E13\u7528\u6A21\u578B,\u652F\u6301\u957F\u8F93\u51FA"}},Xv={"minimax-text-01":{id:"minimax-text-01",displayName:"MiniMax Text-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:90,vision:0,creativity:85,speed:55,cost:70},notes:"4M \u4E0A\u4E0B\u6587\u7A97\u53E3,Lightning Attention + MoE \u67B6\u6784,\u5F00\u6E90\u53EF\u7528"},"minimax-m1-80k":{id:"minimax-m1-80k",displayName:"MiniMax M1-80K",provider:"minimax",maxInputTokens:1e6,maxOutputTokens:8e4,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:92,vision:0,creativity:82,speed:65,cost:75},notes:"1M \u4E0A\u4E0B\u6587 + 80K \u601D\u8003\u9884\u7B97"},"minimax-m2.1":{id:"minimax-m2.1",displayName:"MiniMax M2.1",provider:"minimax",maxInputTokens:2e5,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:88,vision:0,creativity:80,speed:82,cost:85},releaseDate:"2025-12",notes:"\u7F16\u7A0B\u548C Agentic \u5DE5\u4F5C\u6D41\u4F18\u5316,\u652F\u6301\u591A\u8BED\u8A00"},"minimax-vl-01":{id:"minimax-vl-01",displayName:"MiniMax VL-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:92,creativity:88,speed:60,cost:65},notes:"\u591A\u6A21\u6001\u6A21\u578B,\u652F\u6301\u6587\u672C\u548C\u56FE\u50CF"}},Qv={"glm-4.7":{id:"glm-4.7",displayName:"GLM-4.7",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:80,cost:70},releaseDate:"2025-12-22",notes:"\u6700\u65B0\u7248\u672C,200K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA"},"glm-4.6":{id:"glm-4.6",displayName:"GLM-4.6",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:83,creativity:85,speed:82,cost:75},releaseDate:"2025-09-10",notes:"\u4ECE 128K \u6269\u5C55\u81F3 200K \u4E0A\u4E0B\u6587"},"glm-4.5":{id:"glm-4.5",displayName:"GLM-4.5",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:86,reasoning:84,vision:80,creativity:83,speed:85,cost:80},releaseDate:"2025-07"},"glm-4-flash":{id:"glm-4-flash",displayName:"GLM-4 Flash",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:82,reasoning:80,vision:78,creativity:80,speed:95,cost:92},notes:"\u5FEB\u901F\u6A21\u578B,\u76F8\u5F53\u4E8E 300 \u9875\u4E66\u7684\u4E0A\u4E0B\u6587"},"glm-4-plus":{id:"glm-4-plus",displayName:"GLM-4 Plus",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:82,creativity:85,speed:78,cost:65}},"glm-4-air":{id:"glm-4-air",displayName:"GLM-4 Air",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:0,creativity:78,speed:90,cost:88}},"glm-4-long":{id:"glm-4-long",displayName:"GLM-4 Long",provider:"glm",maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:0,creativity:80,speed:50,cost:60},notes:"\u8D85\u957F\u4E0A\u4E0B\u6587\u4E13\u7528,1M tokens"},"glm-4-airx":{id:"glm-4-airx",displayName:"GLM-4 AirX",provider:"glm",maxInputTokens:8e3,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:0,creativity:70,speed:98,cost:98},notes:"\u8D85\u8F7B\u91CF\u7EA7\u6A21\u578B,\u6781\u5FEB\u901F\u5EA6"}},Al=class{models=new Map;constructor(){this.registerModels(Hv),this.registerModels(Jv),this.registerModels(Kv),this.registerModels(Vv),this.registerModels(Yv),this.registerModels(Xv),this.registerModels(Qv);}registerModels(e){for(let[t,s]of Object.entries(e))if(this.models.set(t,s),s.aliases)for(let n of s.aliases)this.models.set(n,s);}getModel(e){return this.models.get(e)}getAllModels(){let e=new Map;for(let t of this.models.values())e.set(t.id,t);return Array.from(e.values())}getModelsByProvider(e){return this.getAllModels().filter(t=>t.provider===e)}hasModel(e){return this.models.has(e)}toModelCapability(e){let t=this.getModel(e);if(t)return {modelAlias:t.id,strengths:this.inferStrengths(t),scores:{coding:t.scores?.coding??50,reasoning:t.scores?.reasoning??50,vision:t.scores?.vision??0,creativity:t.scores?.creativity??50,speed:t.scores?.speed??50,cost:t.scores?.cost??50},features:{supportsVision:t.supportsVision??false,supportsTools:t.supportsTools??false,supportsFunctionCalling:t.supportsFunctionCalling??false,supportsStreaming:t.supportsStreaming??false,maxContextTokens:t.maxInputTokens,maxOutputTokens:t.maxOutputTokens}}}inferStrengths(e){let t=[],s=e.scores??{};return (s.coding??0)>=85&&t.push("coding"),(s.reasoning??0)>=85&&t.push("reasoning"),(s.vision??0)>=85&&t.push("image_analysis"),(s.creativity??0)>=85&&t.push("creative_writing"),t}},Yi=new Al;var us=class{validateParams(e){let t=this.getConstraints(),s=[],n=[];for(let r of Object.keys(e))t.supportedParams.has(r)||n.push(`Parameter '${r}' is not supported by this provider and will be ignored`);if(t.validators){for(let[r,i]of Object.entries(t.validators))if(e[r]!==void 0){let o=i(e[r],e);o===false?s.push(`Invalid value for parameter '${r}': ${e[r]}`):typeof o=="string"&&s.push(`Parameter '${r}': ${o}`);}}if(e.model&&e.max_tokens!==void 0){let r=this.getTokenLimits(e.model);r.found&&e.max_tokens>r.maxInput?s.push(`max_tokens (${e.max_tokens}) exceeds model context window (${r.maxInput}) for ${e.model}`):r.found&&e.max_tokens>r.maxOutput&&n.push(`max_tokens (${e.max_tokens}) exceeds recommended output limit (${r.maxOutput}) for ${e.model}, but is within context window`);}return {valid:s.length===0,errors:s,warnings:n.length>0?n:void 0}}getTokenLimits(e){let t=Yi.getModel(e);if(t)return {maxOutput:t.maxOutputTokens,maxInput:t.maxInputTokens,found:true,source:"model"};let s=this.getConstraints(),n=s.maxOutputTokens[e],r=s.maxInputTokens[e];if(n!==void 0&&r!==void 0)return {maxOutput:n,maxInput:r,found:true,source:"model"};for(let[i,o]of Object.entries(s.maxOutputTokens))if(this.matchPattern(e,i))return {maxOutput:o,maxInput:s.maxInputTokens[i]||128e3,found:true,source:"model"};return {maxOutput:4096,maxInput:128e3,found:false,source:"fallback"}}normalizeParams(e){let t=this.getConstraints(),s={};for(let[n,r]of Object.entries(e)){let i=t.paramAliases?.[n]||n;t.supportedParams.has(n)&&(s[i]=r);}if(t.defaults)for(let[n,r]of Object.entries(t.defaults))s[n]===void 0&&(s[n]=r);return s}matchPattern(e,t){return t.includes("*")?new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e):e===t}isParamSupported(e){return this.getConstraints().supportedParams.has(e)}getParamAlias(e){return this.getConstraints().paramAliases?.[e]||e}};function Ve(a,e){return t=>{let s=Number(t);return isNaN(s)?"Must be a number":s<a||s>e?`Must be between ${a} and ${e}`:true}}function yn(a){return e=>a.includes(e)?true:`Must be one of: ${a.join(", ")}`}function Np(a){return e=>{let t=typeof e;return t!==a?`Expected ${a}, got ${t}`:true}}function Xi(...a){return (e,t)=>{for(let s of a){let n=s(e,t);if(n!==true)return n}return true}}var Is=class extends us{getConstraints(){return {maxOutputTokens:{"gpt-4o":16384,"gpt-4o-2024-11-20":16384,"gpt-4o-2024-08-06":16384,"gpt-4o-2024-05-13":4096,"gpt-4o-mini":16384,"gpt-4o-mini-2024-07-18":16384,"gpt-4-turbo":4096,"gpt-4-turbo-2024-04-09":4096,"gpt-4-turbo-preview":4096,"gpt-4-0125-preview":4096,"gpt-4-1106-preview":4096,"gpt-4":8192,"gpt-4-0613":8192,"gpt-4-0314":8192,"gpt-3.5-turbo":4096,"gpt-3.5-turbo-0125":4096,"gpt-3.5-turbo-1106":4096,o1:1e5,"o1-2024-12-17":1e5,"o1-preview":32768,"o1-preview-2024-09-12":32768,"o1-mini":65536,"o1-mini-2024-09-12":65536,o3:1e5,"o3-mini":1e5,"o3-mini-2025-01-31":1e5,"o4-mini":1e5,"gpt-5":1e5,"gpt-5.1":1e5,"gpt-5.1-codex":1e5,"gpt-5.1-codex-max":1e5,"gpt-5.1-codex-mini":1e5,"gpt-5.2":1e5,"gpt-5.2-codex":1e5,"gpt-5-codex":1e5,"gpt-5-codex-mini":1e5,"codex-mini-latest":1e5,"gpt-4.1":1e5,"gpt-4.1-2025-04-14":1e5,"gpt-4o*":16384,"gpt-4-turbo*":4096,"gpt-4.1*":1e5,"gpt-4*":8192,"gpt-3.5*":4096,"gpt-5*":1e5,"codex*":1e5,"o1*":1e5,"o3*":1e5,"o4*":1e5},maxInputTokens:{"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4-turbo":128e3,"gpt-4-turbo-2024-04-09":128e3,"gpt-4.1":1047576,"gpt-4.1-2025-04-14":1047576,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,"gpt-5":272e3,"gpt-5.1":272e3,"gpt-5.1-codex":272e3,"gpt-5.1-codex-max":272e3,"gpt-5.1-codex-mini":272e3,"gpt-5-codex":272e3,"gpt-5-codex-mini":272e3,"gpt-5.2":4e5,"gpt-5.2-codex":4e5,"codex-mini-latest":2e5,o1:2e5,"o1-preview":128e3,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"gpt-4o*":128e3,"gpt-4-turbo*":128e3,"gpt-4.1*":1047576,"gpt-5*":272e3,"gpt-5.2*":4e5,"codex*":272e3,"o1*":2e5,"o3*":2e5,"o4*":2e5},supportedParams:new Set(["model","messages","stream","stream_options","max_tokens","max_completion_tokens","temperature","top_p","top_k","frequency_penalty","presence_penalty","stop","n","seed","reasoning_effort","verbosity","tools","tool_choice","parallel_tool_calls","response_format","logprobs","top_logprobs","logit_bias","modalities","audio","user","safety_identifier","store","service_tier","prompt_cache_key","prompt_cache_retention","metadata","prediction","extra_body","search_parameters","web_search_options"]),validators:{temperature:Ve(0,2),top_p:Ve(0,1),frequency_penalty:Ve(-2,2),presence_penalty:Ve(-2,2),reasoning_effort:yn(["low","medium","high"]),verbosity:yn(["low","medium","high"]),tool_choice:e=>typeof e=="string"?["none","auto","required"].includes(e)||"Must be 'none', 'auto', or 'required'":typeof e=="object"&&e.type==="function"?true:"Invalid tool_choice format","response_format.type":yn(["text","json_object","json_schema"]),stream:e=>typeof e=="boolean"||"Must be a boolean",n:Xi(e=>typeof e=="number"||"Must be a number",Ve(1,10)),max_tokens:(e,t)=>{let s=Number(e);if(isNaN(s))return "Must be a number";if(s<1)return "Must be at least 1";t?.model||"";return true}},defaults:{temperature:1,top_p:1,n:1,stream:false,max_tokens:4096}}}isResponsesAPIModel(e){return e.startsWith("o1")||e.startsWith("o3")}supportsReasoning(e){return this.isResponsesAPIModel(e)}supportsVision(e){return e.includes("gpt-4o")||e.includes("gpt-4-turbo")||e.includes("gpt-4-vision")}supportsTools(e){return e.startsWith("o1-preview")||e.startsWith("o1-mini")?false:e.includes("gpt-4")||e.includes("gpt-3.5-turbo")||e.startsWith("o3")}getRecommendedMaxTokens(e,t){let s=this.getTokenLimits(e);switch(t){case "short":return Math.min(1024,s.maxOutput);case "medium":return Math.min(4096,s.maxOutput);case "long":return s.maxOutput;default:return Math.min(4096,s.maxOutput)}}};var ds=class{combinePromptSections(e){return e.filter(s=>s.content.trim().length>0).sort((s,n)=>(s.order||0)-(n.order||0)).map(s=>s.title?`# ${s.title}
1505
1505
 
1506
1506
  ${s.content}`:s.content).join(`
1507
1507
 
1508
1508
  `)}getWorkingDirectorySection(e,t){return t==="zh"?{title:"\u5DE5\u4F5C\u76EE\u5F55",content:`\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55: ${e}`,order:10}:{title:"Working Directory",content:`Current working directory: ${e}`,order:10}}modelMatches(e,t){return e?t.includes("*")?new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e):e===t:false}isModelType(e,...t){return e?t.some(s=>this.modelMatches(e,s)):false}};function Ms(a){return a.replace(/\n{3,}/g,`
1509
1509
 
1510
- `).trim()}var Qv=`You are Claude Code, Anthropic's official CLI for Claude.
1510
+ `).trim()}var Zv=`You are Claude Code, Anthropic's official CLI for Claude.
1511
1511
 
1512
1512
  You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
1513
1513
 
@@ -1545,7 +1545,7 @@ When planning tasks, provide concrete implementation steps without time estimate
1545
1545
  You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
1546
1546
  These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
1547
1547
 
1548
- It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.`.trim(),Ps=class extends ds{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:r}=e;return this.isResponsesAPIModel(n)?this.buildResponsesAPIPrompt(r):this.buildChatCompletionsPrompt(t,s,n,r)}buildResponsesAPIPrompt(e){let t=Qv;return e&&e.trim()&&(t+=`
1548
+ It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.`.trim(),Ps=class extends ds{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:r}=e;return this.isResponsesAPIModel(n)?this.buildResponsesAPIPrompt(r):this.buildChatCompletionsPrompt(t,s,n,r)}buildResponsesAPIPrompt(e){let t=Zv;return e&&e.trim()&&(t+=`
1549
1549
 
1550
1550
  # Custom Instructions
1551
1551
 
@@ -1619,12 +1619,12 @@ Tool results are returned via messages with role "tool".`}getGeneralRules(e){ret
1619
1619
  1. **Accuracy First**: Ensure correctness of code and suggestions
1620
1620
  2. **Be Concise**: Avoid redundancy, answer directly
1621
1621
  3. **Safety First**: No malicious code, be aware of security risks
1622
- 4. **Stay Professional**: Objective, technical communication style`}getModelDisplayName(e){return e?e.includes("o3")?"OpenAI o3":e.includes("o1")?"OpenAI o1":e.includes("gpt-4o")?"GPT-4o":e.includes("gpt-4")?"GPT-4":e.includes("gpt-3.5")?"GPT-3.5":e:"GPT-4"}isResponsesAPIModel(e){return this.isModelType(e,"o1*","o3*")}supportsVision(e){return this.isModelType(e,"gpt-4o*","gpt-4-turbo*","gpt-4-vision*")}};W();var rw=16e3;function $p(a,e=rw){if(!a||a.length<=e)return a;let t=a.split(`
1622
+ 4. **Stay Professional**: Objective, technical communication style`}getModelDisplayName(e){return e?e.includes("o3")?"OpenAI o3":e.includes("o1")?"OpenAI o1":e.includes("gpt-4o")?"GPT-4o":e.includes("gpt-4")?"GPT-4":e.includes("gpt-3.5")?"GPT-3.5":e:"GPT-4"}isResponsesAPIModel(e){return this.isModelType(e,"o1*","o3*")}supportsVision(e){return this.isModelType(e,"gpt-4o*","gpt-4-turbo*","gpt-4-vision*")}};W();var iw=16e3;function $p(a,e=iw){if(!a||a.length<=e)return a;let t=a.split(`
1623
1623
  `).length,s=a.length,n=Math.floor(e*.4),r=Math.floor(e*.4),i=n,o=a.length-r;for(;i>0&&(a.charCodeAt(i)&192)===128;)i--;for(;o<a.length&&(a.charCodeAt(o)&192)===128;)o++;let l=a.slice(0,i),c=a.slice(o),d=`
1624
1624
 
1625
1625
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1626
1626
 
1627
- `;return l+d+c}function Fp(a,e={}){let t={...a};return !e.allowServiceTier&&"service_tier"in t&&delete t.service_tier,e.disableStore&&"store"in t&&delete t.store,!e.allowSafetyIdentifier&&"safety_identifier"in t&&delete t.safety_identifier,t}function jp(a,e){if(!a)return null;if(e?.reasoning)return {effort:e.reasoning.effort||"low",verbosity:e.reasoning.verbosity||"low",summary:e.reasoning.summary||"auto"};let t=process.env.CD_REASONING_EFFORT||process.env.NEOX_REASONING_EFFORT,s=process.env.CD_REASONING_VERBOSITY||process.env.NEOX_REASONING_VERBOSITY,n=process.env.CD_REASONING_SUMMARY||process.env.NEOX_REASONING_SUMMARY;return t||s||n?{effort:t||"low",verbosity:s||"low",summary:n||"auto"}:null}var Vt=class{client;defaultModel;isProxy;useResponsesAPI;apiEndpoint;streamFormat;retryConfig;baseUrl;privacySettings;sessionId;doubaoThinking;apiKey;modelConfig;structuredOutputMode;constructor(e){this.baseUrl=e.baseUrl||"https://api.openai.com/v1",this.isProxy=e.baseUrl?!e.baseUrl.includes("api.openai.com"):false,this.useResponsesAPI=e.useResponsesAPI||false,this.apiEndpoint=e.apiEndpoint||"/chat/completions",this.streamFormat=e.streamFormat||"openai",this.apiKey=e.apiKey,this.sessionId=e.sessionId||`session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,this.privacySettings=e.privacySettings||{},this.doubaoThinking=e.doubaoThinking,this.modelConfig=e.modelConfig,this.structuredOutputMode=e.structuredOutputMode||"json_schema",this.client=Zv.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:12e4}),this.defaultModel=e.defaultModel||"gpt-4";let t=dn("openai",this.baseUrl);this.retryConfig=is(void 0,{...t,...e.retry}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Initialized with:",{baseUrl:this.baseUrl,isProxy:this.isProxy,useResponsesAPI:this.useResponsesAPI,apiEndpoint:this.apiEndpoint,streamFormat:this.streamFormat});}async chat(e,t={}){let{model:s=this.defaultModel}=t;return this.shouldUseResponsesAPI(s)?this.chatWithResponsesAPI(e,t):this.chatWithChatCompletions(e,t)}async*chatStreamed(e,t={}){let{model:s=this.defaultModel}=t;this.shouldUseResponsesAPI(s)?yield*this.chatStreamedWithResponsesAPI(e,t):yield*this.chatStreamedWithChatCompletions(e,t);}async chatWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:r=.7,maxInputTokens:i}=t,o=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:r,structuredOutput:t.structuredOutput,maxInputTokens:i,stream:false}),l=`${this.client.defaults.baseURL}/chat/completions`;ge.llmRequest("openai",s,o,l,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Request",{url:l,payload:o});let c=this.retryConfig.requestMaxRetries,u=null;for(let d=0;d<=c;d++)try{let p=Date.now(),h=await this.client.post("/chat/completions",o),g=Date.now()-p;return ge.llmResponse("openai",g,h.data.usage,h.data.choices[0]),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Response",{duration:`${g}ms`,data:h.data}),h.data}catch(p){u=p;let h=ft(p);if(m.error("OpenAI",`Request Error - URL: ${l}`),m.error("OpenAI",`Error: ${p.message}`),p.response?.data)try{let y=p.response.data;if(typeof y=="string")m.error("OpenAI",`Response: ${y.substring(0,500)}`);else if(y&&typeof y=="object"){let w={error:y.error,message:y.message,type:y.type,code:y.code};m.error("OpenAI",`Response: ${JSON.stringify(w).substring(0,500)}`);}}catch{m.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Error",{url:l,message:p.message,category:h.category,retryable:h.retryable,attempt:`${d+1}/${c+1}`}),ge.llmError("openai",p),!h.retryable||d===c)throw h;let g=p.response?.headers?.["retry-after"],f=Jt(g),b=os(f,d+1,this.retryConfig);m.info("OpenAI",`Request failed (${h.code}), retrying in ${nt(b)} (${d+1}/${c})...`),await gn(b);}throw u||new Error("Unknown error during retry")}async*chatStreamedWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:r=.7,maxInputTokens:i,signal:o}=t,l=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:r,structuredOutput:t.structuredOutput,maxInputTokens:i,stream:true}),c=`${this.client.defaults.baseURL}${this.apiEndpoint}`;ge.llmRequest("openai-stream",s,l,c,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Stream Request",{url:c,endpoint:this.apiEndpoint,payload:l});let u=this.retryConfig.streamMaxRetries,d=0;for(;;)try{if(o?.aborted){let f=new Error("Request aborted");throw f.name="AbortError",f}let p=Date.now(),h=await this.client.post(this.apiEndpoint,l,{responseType:"stream",signal:o});if(process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Stream Started",{status:h.status}),h.status!==200){let f="";for await(let b of h.data)f+=b.toString();throw new Error(`OpenAI API error: ${h.status} - ${f}`)}this.streamFormat==="anthropic"?yield*this.parseAnthropicStreamResponse(h.data):yield*this.parseOpenAIStreamResponse(h.data,o);let g=Date.now()-p;ge.llmResponse("openai-stream",g,{},{}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Stream Complete",{duration:`${g}ms`});return}catch(p){let h=ft(p);if(m.error("OpenAI",`Stream Error - Request URL: ${c}`),m.error("OpenAI",`Error: ${p.message}`),p.response?.data)try{let g=p.response.data;if(typeof g=="string")m.error("OpenAI",`Response: ${g.substring(0,500)}`);else if(g&&typeof g=="object"){let f={error:g.error,message:g.message,type:g.type,code:g.code};m.error("OpenAI",`Response: ${JSON.stringify(f).substring(0,500)}`);}}catch{m.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Stream Error Details",{url:c,message:p.message,retryable:h.retryable,status:p.response?.status}),ge.llmError("openai-stream",p),h.retryable&&d<u){d++;let g=p.response?.headers?.["retry-after"],f=Jt(g),b=os(f,d,this.retryConfig);m.info("OpenAI",`Stream failed (${h.code}), reconnecting in ${nt(b)} (${d}/${u})...`),yield {choices:[],type:"stream_retry",error:h.message,errorCode:h.code,attempt:d,maxRetries:u,delayMs:b};try{await As(b,o);}catch(y){throw y?.name==="AbortError",y}continue}throw h}}buildChatCompletionsPayload(e,t){let{model:s,tools:n,temperature:r,structuredOutput:i,maxInputTokens:o,stream:l}=t,c=this.formatMessagesForChatCompletions(e);if(this.baseUrl.includes("ark.cn-beijing.volces.com")){let h={model:s,messages:c,stream:l};return this.doubaoThinking&&s.includes("doubao-seed")&&(h.thinking={type:this.doubaoThinking.type},process.env.CLI_DEBUG==="1"&&m.debug("OpenAI",`Doubao thinking mode: ${this.doubaoThinking.type}`)),n&&n.length>0&&(h.tools=n.map(g=>({type:"function",function:{name:g.name,description:g.description,parameters:g.parameters}})),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI",`Added ${h.tools.length} tools to Doubao payload`)),h}let d={model:s,messages:c,temperature:r,stream:l};l&&(d.stream_options={include_usage:true}),o!==void 0&&(d.max_tokens=o);let p=jp(false);return p&&(d.reasoning_effort=p.effort,p.verbosity&&(d.verbosity=p.verbosity)),n&&n.length>0&&(d.tools=n.map(h=>({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI",`Added ${d.tools.length} tools to Chat Completions payload`)),i&&(this.structuredOutputMode==="json_object"?d.response_format={type:"json_object"}:d.response_format={type:"json_schema",json_schema:{name:i.name,schema:i.schema,strict:i.strict??true}}),Fp(d,this.privacySettings)}formatMessagesForChatCompletions(e){return e.filter(t=>{let s=t.content&&(typeof t.content=="string"?t.content.trim().length>0:Array.isArray(t.content)&&t.content.length>0),n=t.tool_calls&&t.tool_calls.length>0;return s||n}).map(t=>{let s={role:t.role,content:null};if(t.role==="tool"){let n=typeof t.content=="string"?t.content:me(t.content);s.content=$p(n);}else Array.isArray(t.content)?s.content=t.content:t.tool_calls&&t.tool_calls.length>0?s.content=t.content||"":s.content=t.content||null;return t.name&&(s.name=t.name),t.tool_call_id&&(s.tool_call_id=t.tool_call_id),t.tool_calls&&(s.tool_calls=t.tool_calls.map(n=>({id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}))),s})}async chatWithResponsesAPI(e,t){let s="",n=[],r;for await(let i of this.chatStreamedWithResponsesAPI(e,t)){let o=i.choices?.[0]?.delta;if(o&&(o.content&&(s+=o.content),o.tool_calls))for(let l of o.tool_calls){let c=n.find(u=>u.index===l.index);c?l.function?.arguments&&(c.function.arguments+=l.function.arguments):n.push({id:l.id||`call_${n.length}`,type:"function",function:{name:l.function?.name||"",arguments:l.function?.arguments||""},index:l.index});}i.usage&&(r=i.usage);}return {id:`chatcmpl-${Date.now()}`,choices:[{message:{role:"assistant",content:s||null,...n.length>0?{tool_calls:n}:{}},finish_reason:"stop"}],usage:r||{total_tokens:0,prompt_tokens:0,completion_tokens:0}}}async*chatStreamedWithResponsesAPI(e,t){let{model:s=this.defaultModel,tools:n,temperature:r=.7,structuredOutput:i,maxInputTokens:o,signal:l}=t,c=this.buildResponsesAPIPayload(e,{model:s,tools:n,temperature:r,structuredOutput:i,maxInputTokens:o}),u=`${this.client.defaults.baseURL}/responses`;if(ge.llmRequest("openai-responses-stream",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"){m.info("OpenAI","Responses API Stream Request",{url:u,toolsCount:c.tools?.length||0}),process.env.CLI_DEBUG_PAYLOAD==="1"&&m.debug("OpenAI","Full Payload",c);let d=['-H "Content-Type: application/json"','-H "Accept: text/event-stream"',`-H "Authorization: Bearer ${this.apiKey}"`,`-H "conversation_id: ${this.sessionId}"`,`-H "session_id: ${this.sessionId}"`,'-H "user-agent: neox-cli/1.0.0"'],p=[`curl -X POST "${u}"`,...d,`-d '${JSON.stringify(c)}'`,"--no-buffer"].join(` \\
1627
+ `;return l+d+c}function Fp(a,e={}){let t={...a};return !e.allowServiceTier&&"service_tier"in t&&delete t.service_tier,e.disableStore&&"store"in t&&delete t.store,!e.allowSafetyIdentifier&&"safety_identifier"in t&&delete t.safety_identifier,t}function jp(a,e){if(!a)return null;if(e?.reasoning)return {effort:e.reasoning.effort||"low",verbosity:e.reasoning.verbosity||"low",summary:e.reasoning.summary||"auto"};let t=process.env.CD_REASONING_EFFORT||process.env.NEOX_REASONING_EFFORT,s=process.env.CD_REASONING_VERBOSITY||process.env.NEOX_REASONING_VERBOSITY,n=process.env.CD_REASONING_SUMMARY||process.env.NEOX_REASONING_SUMMARY;return t||s||n?{effort:t||"low",verbosity:s||"low",summary:n||"auto"}:null}var Vt=class{client;defaultModel;isProxy;useResponsesAPI;apiEndpoint;streamFormat;retryConfig;baseUrl;privacySettings;sessionId;doubaoThinking;apiKey;modelConfig;structuredOutputMode;constructor(e){this.baseUrl=e.baseUrl||"https://api.openai.com/v1",this.isProxy=e.baseUrl?!e.baseUrl.includes("api.openai.com"):false,this.useResponsesAPI=e.useResponsesAPI||false,this.apiEndpoint=e.apiEndpoint||"/chat/completions",this.streamFormat=e.streamFormat||"openai",this.apiKey=e.apiKey,this.sessionId=e.sessionId||`session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,this.privacySettings=e.privacySettings||{},this.doubaoThinking=e.doubaoThinking,this.modelConfig=e.modelConfig,this.structuredOutputMode=e.structuredOutputMode||"json_schema",this.client=ew.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:12e4}),this.defaultModel=e.defaultModel||"gpt-4";let t=dn("openai",this.baseUrl);this.retryConfig=is(void 0,{...t,...e.retry}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Initialized with:",{baseUrl:this.baseUrl,isProxy:this.isProxy,useResponsesAPI:this.useResponsesAPI,apiEndpoint:this.apiEndpoint,streamFormat:this.streamFormat});}async chat(e,t={}){let{model:s=this.defaultModel}=t;return this.shouldUseResponsesAPI(s)?this.chatWithResponsesAPI(e,t):this.chatWithChatCompletions(e,t)}async*chatStreamed(e,t={}){let{model:s=this.defaultModel}=t;this.shouldUseResponsesAPI(s)?yield*this.chatStreamedWithResponsesAPI(e,t):yield*this.chatStreamedWithChatCompletions(e,t);}async chatWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:r=.7,maxInputTokens:i}=t,o=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:r,structuredOutput:t.structuredOutput,maxInputTokens:i,stream:false}),l=`${this.client.defaults.baseURL}/chat/completions`;ge.llmRequest("openai",s,o,l,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Request",{url:l,payload:o});let c=this.retryConfig.requestMaxRetries,u=null;for(let d=0;d<=c;d++)try{let p=Date.now(),h=await this.client.post("/chat/completions",o),g=Date.now()-p;return ge.llmResponse("openai",g,h.data.usage,h.data.choices[0]),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Response",{duration:`${g}ms`,data:h.data}),h.data}catch(p){u=p;let h=ft(p);if(m.error("OpenAI",`Request Error - URL: ${l}`),m.error("OpenAI",`Error: ${p.message}`),p.response?.data)try{let y=p.response.data;if(typeof y=="string")m.error("OpenAI",`Response: ${y.substring(0,500)}`);else if(y&&typeof y=="object"){let w={error:y.error,message:y.message,type:y.type,code:y.code};m.error("OpenAI",`Response: ${JSON.stringify(w).substring(0,500)}`);}}catch{m.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Error",{url:l,message:p.message,category:h.category,retryable:h.retryable,attempt:`${d+1}/${c+1}`}),ge.llmError("openai",p),!h.retryable||d===c)throw h;let g=p.response?.headers?.["retry-after"],f=Jt(g),b=os(f,d+1,this.retryConfig);m.info("OpenAI",`Request failed (${h.code}), retrying in ${nt(b)} (${d+1}/${c})...`),await gn(b);}throw u||new Error("Unknown error during retry")}async*chatStreamedWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:r=.7,maxInputTokens:i,signal:o}=t,l=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:r,structuredOutput:t.structuredOutput,maxInputTokens:i,stream:true}),c=`${this.client.defaults.baseURL}${this.apiEndpoint}`;ge.llmRequest("openai-stream",s,l,c,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Chat Completions Stream Request",{url:c,endpoint:this.apiEndpoint,payload:l});let u=this.retryConfig.streamMaxRetries,d=0;for(;;)try{if(o?.aborted){let f=new Error("Request aborted");throw f.name="AbortError",f}let p=Date.now(),h=await this.client.post(this.apiEndpoint,l,{responseType:"stream",signal:o});if(process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Stream Started",{status:h.status}),h.status!==200){let f="";for await(let b of h.data)f+=b.toString();throw new Error(`OpenAI API error: ${h.status} - ${f}`)}this.streamFormat==="anthropic"?yield*this.parseAnthropicStreamResponse(h.data):yield*this.parseOpenAIStreamResponse(h.data,o);let g=Date.now()-p;ge.llmResponse("openai-stream",g,{},{}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Stream Complete",{duration:`${g}ms`});return}catch(p){let h=ft(p);if(m.error("OpenAI",`Stream Error - Request URL: ${c}`),m.error("OpenAI",`Error: ${p.message}`),p.response?.data)try{let g=p.response.data;if(typeof g=="string")m.error("OpenAI",`Response: ${g.substring(0,500)}`);else if(g&&typeof g=="object"){let f={error:g.error,message:g.message,type:g.type,code:g.code};m.error("OpenAI",`Response: ${JSON.stringify(f).substring(0,500)}`);}}catch{m.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Stream Error Details",{url:c,message:p.message,retryable:h.retryable,status:p.response?.status}),ge.llmError("openai-stream",p),h.retryable&&d<u){d++;let g=p.response?.headers?.["retry-after"],f=Jt(g),b=os(f,d,this.retryConfig);m.info("OpenAI",`Stream failed (${h.code}), reconnecting in ${nt(b)} (${d}/${u})...`),yield {choices:[],type:"stream_retry",error:h.message,errorCode:h.code,attempt:d,maxRetries:u,delayMs:b};try{await As(b,o);}catch(y){throw y?.name==="AbortError",y}continue}throw h}}buildChatCompletionsPayload(e,t){let{model:s,tools:n,temperature:r,structuredOutput:i,maxInputTokens:o,stream:l}=t,c=this.formatMessagesForChatCompletions(e);if(this.baseUrl.includes("ark.cn-beijing.volces.com")){let h={model:s,messages:c,stream:l};return this.doubaoThinking&&s.includes("doubao-seed")&&(h.thinking={type:this.doubaoThinking.type},process.env.CLI_DEBUG==="1"&&m.debug("OpenAI",`Doubao thinking mode: ${this.doubaoThinking.type}`)),n&&n.length>0&&(h.tools=n.map(g=>({type:"function",function:{name:g.name,description:g.description,parameters:g.parameters}})),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI",`Added ${h.tools.length} tools to Doubao payload`)),h}let d={model:s,messages:c,temperature:r,stream:l};l&&(d.stream_options={include_usage:true}),o!==void 0&&(d.max_tokens=o);let p=jp(false);return p&&(d.reasoning_effort=p.effort,p.verbosity&&(d.verbosity=p.verbosity)),n&&n.length>0&&(d.tools=n.map(h=>({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI",`Added ${d.tools.length} tools to Chat Completions payload`)),i&&(this.structuredOutputMode==="json_object"?d.response_format={type:"json_object"}:d.response_format={type:"json_schema",json_schema:{name:i.name,schema:i.schema,strict:i.strict??true}}),Fp(d,this.privacySettings)}formatMessagesForChatCompletions(e){return e.filter(t=>{let s=t.content&&(typeof t.content=="string"?t.content.trim().length>0:Array.isArray(t.content)&&t.content.length>0),n=t.tool_calls&&t.tool_calls.length>0;return s||n}).map(t=>{let s={role:t.role,content:null};if(t.role==="tool"){let n=typeof t.content=="string"?t.content:me(t.content);s.content=$p(n);}else Array.isArray(t.content)?s.content=t.content:t.tool_calls&&t.tool_calls.length>0?s.content=t.content||"":s.content=t.content||null;return t.name&&(s.name=t.name),t.tool_call_id&&(s.tool_call_id=t.tool_call_id),t.tool_calls&&(s.tool_calls=t.tool_calls.map(n=>({id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}))),s})}async chatWithResponsesAPI(e,t){let s="",n=[],r;for await(let i of this.chatStreamedWithResponsesAPI(e,t)){let o=i.choices?.[0]?.delta;if(o&&(o.content&&(s+=o.content),o.tool_calls))for(let l of o.tool_calls){let c=n.find(u=>u.index===l.index);c?l.function?.arguments&&(c.function.arguments+=l.function.arguments):n.push({id:l.id||`call_${n.length}`,type:"function",function:{name:l.function?.name||"",arguments:l.function?.arguments||""},index:l.index});}i.usage&&(r=i.usage);}return {id:`chatcmpl-${Date.now()}`,choices:[{message:{role:"assistant",content:s||null,...n.length>0?{tool_calls:n}:{}},finish_reason:"stop"}],usage:r||{total_tokens:0,prompt_tokens:0,completion_tokens:0}}}async*chatStreamedWithResponsesAPI(e,t){let{model:s=this.defaultModel,tools:n,temperature:r=.7,structuredOutput:i,maxInputTokens:o,signal:l}=t,c=this.buildResponsesAPIPayload(e,{model:s,tools:n,temperature:r,structuredOutput:i,maxInputTokens:o}),u=`${this.client.defaults.baseURL}/responses`;if(ge.llmRequest("openai-responses-stream",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"){m.info("OpenAI","Responses API Stream Request",{url:u,toolsCount:c.tools?.length||0}),process.env.CLI_DEBUG_PAYLOAD==="1"&&m.debug("OpenAI","Full Payload",c);let d=['-H "Content-Type: application/json"','-H "Accept: text/event-stream"',`-H "Authorization: Bearer ${this.apiKey}"`,`-H "conversation_id: ${this.sessionId}"`,`-H "session_id: ${this.sessionId}"`,'-H "user-agent: neox-cli/1.0.0"'],p=[`curl -X POST "${u}"`,...d,`-d '${JSON.stringify(c)}'`,"--no-buffer"].join(` \\
1628
1628
  `),h=[`curl -X POST "${u}"`,...d,`-d '${JSON.stringify(c)}'`,"--no-buffer"].join(" ");m.info("CURL","\u2550".repeat(80)),m.info("CURL","Multi-line CURL command:"),m.info("CURL",p),m.info("CURL","\u2550".repeat(80)),m.info("CURL","One-line CURL (copy-paste ready):"),m.info("CURL",h),m.info("CURL","\u2550".repeat(80));}try{if(l?.aborted){let f=new Error("Request aborted");throw f.name="AbortError",f}let d=Date.now(),p={Accept:"text/event-stream",conversation_id:this.sessionId,session_id:this.sessionId,originator:"codex_cli_rs","x-codex-beta-features":"shell_snapshot"},h=await this.client.post("/responses",c,{responseType:"stream",signal:l,headers:p});if(process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Responses API Stream Started",{status:h.status}),h.status!==200){let f="";for await(let y of h.data)f+=y.toString();let b=_s(f,h.status);throw new Error(`OpenAI Responses API error: ${h.status} - ${b.message}`)}yield*this.parseResponsesAPIStream(h.data,l);let g=Date.now()-d;ge.llmResponse("openai-responses-stream",g,{},{}),process.env.CLI_DEBUG==="1"&&m.debug("OpenAI","Responses API Stream Complete",{duration:`${g}ms`});}catch(d){let p,h=d.response?.status;if(d.response?.data){let f=d.response.data;try{if(f&&typeof f.on=="function"){let b="";try{for await(let y of f)b+=y.toString();p=b;}catch{p="[Could not read error stream]";}}else if(typeof f=="string")p=f;else if(f&&typeof f=="object"){let b={error:f.error,message:f.message,type:f.type,code:f.code};p=JSON.stringify(b);}}catch{p="[Could not parse error data]";}}process.env.CLI_DEBUG==="1"&&m.error("OpenAI","Responses API Stream Error",{status:h,errorData:p,message:d.message}),ge.llmError("openai-responses-stream",d);let g;if(h&&p){let f=_s(p,h);g=`${f.message}${f.detail?`
1629
1629
  `+f.detail:""}`;}else g=d.message||"Unknown error";throw new Error(g)}}buildResponsesAPIPayload(e,t){let{model:s,tools:n,temperature:r,structuredOutput:i,maxInputTokens:o}=t,l=this.convertToResponsesInput(e),c=this.buildResponsesInstructions(e);if(!c)throw new Error("[OpenAI Responses API] instructions field is required but no system message found");if(!l||l.length===0)throw new Error("[OpenAI Responses API] input array is empty - at least one user message is required");if(process.env.CLI_DEBUG==="1"){m.debug("OpenAI","Building Responses API payload",{instructionsLength:c.length,instructionsPreview:c.substring(0,300),inputItems:l.length,inputPreview:JSON.stringify(l.slice(0,2),null,2)}),m.debug("OpenAI","Full input array for Response API:",{totalMessages:e.length,messageRoles:e.map(b=>b.role),inputCount:l.length,fullInput:JSON.stringify(l,null,2)});let p=l.filter(b=>b.type==="function_call"),h=l.filter(b=>b.type==="function_call_output");m.debug("OpenAI","Function call ID matching check:",{callCount:p.length,outputCount:h.length,callIds:p.map(b=>({id:b.id||b.call_id,name:b.name})),outputIds:h.map(b=>({call_id:b.call_id}))});let g=new Set(p.map(b=>b.call_id||b.id)),f=h.filter(b=>!g.has(b.call_id));f.length>0&&m.warn("OpenAI",`\u26A0\uFE0F Found ${f.length} unmatched function_call_output!`,{unmatchedCallIds:f.map(b=>b.call_id)});}let u={model:s,instructions:c,input:l};n&&n.length>0&&(u.tools=n.map(p=>this.formatResponsesFunctionTool(p)),u.tool_choice="auto",u.parallel_tool_calls=true,process.env.CLI_DEBUG==="1"&&m.debug("OpenAI",`Added ${u.tools.length} tools`));let d=jp(true,this.modelConfig);return d&&(u.reasoning={effort:d.effort,summary:d.summary||"auto"}),u.store=false,u.stream=true,d&&(u.include=["reasoning.encrypted_content"]),u.prompt_cache_key=this.sessionId,Fp(u,this.privacySettings)}buildResponsesInstructions(e){let t=Ji({workDir:process.cwd(),language:"zh",useCodexStyle:true});return process.env.CLI_DEBUG==="1"&&(m.debug("OpenAI","Using official Codex instructions for Responses API"),m.debug("OpenAI",`Instructions length: ${t.length} chars`),m.debug("OpenAI",`Instructions preview: ${t.substring(0,200)}...`)),t}convertToResponsesInput(e){let s=this.filterIncompleteToolCalls(e).filter(i=>i.role!=="system").flatMap(i=>this.convertMessageToResponsesItems(i)),n=this.extractMemoryContext(e);n&&s.unshift({type:"message",role:"user",status:"completed",content:[{type:"input_text",text:`<memory_context>
1630
1630
  ${n}
@@ -1688,21 +1688,21 @@ Claude uses standard tool calling format:
1688
1688
  }
1689
1689
  \`\`\`
1690
1690
 
1691
- Tool results are returned via tool_result messages.`}supportsExtendedThinking(e){return e?e.includes("claude-3-5-sonnet")||e.includes("claude-3-opus"):false}supportsPromptCaching(e){return e?e.includes("claude-3-5")||e.includes("claude-3-opus")||e.includes("claude-3-sonnet"):false}getCachingRecommendation(e){return e<2e3?{shouldUseCache:false,cacheTTL:"5m",reason:"Prompt too short, caching overhead not worth it"}:e<1e4?{shouldUseCache:true,cacheTTL:"5m",reason:"Medium prompt, 5-minute cache recommended"}:{shouldUseCache:true,cacheTTL:"1h",reason:"Long prompt, 1-hour cache recommended for cost savings"}}};W();var ow=15e3,Sr=2*1024*1024,aw=1.5*1024*1024;function lw(a,e=ow){if(!a||a.length<=e)return a;let t=a.split(`
1691
+ Tool results are returned via tool_result messages.`}supportsExtendedThinking(e){return e?e.includes("claude-3-5-sonnet")||e.includes("claude-3-opus"):false}supportsPromptCaching(e){return e?e.includes("claude-3-5")||e.includes("claude-3-opus")||e.includes("claude-3-sonnet"):false}getCachingRecommendation(e){return e<2e3?{shouldUseCache:false,cacheTTL:"5m",reason:"Prompt too short, caching overhead not worth it"}:e<1e4?{shouldUseCache:true,cacheTTL:"5m",reason:"Medium prompt, 5-minute cache recommended"}:{shouldUseCache:true,cacheTTL:"1h",reason:"Long prompt, 1-hour cache recommended for cost savings"}}};W();var aw=15e3,Sr=2*1024*1024,lw=1.5*1024*1024;function cw(a,e=aw){if(!a||a.length<=e)return a;let t=a.split(`
1692
1692
  `).length,s=a.length,n=Math.floor(e*.4),r=Math.floor(e*.4),i=n,o=a.length-r;for(;i>0&&(a.charCodeAt(i)&192)===128;)i--;for(;o<a.length&&(a.charCodeAt(o)&192)===128;)o++;let l=a.slice(0,i),c=a.slice(o),d=`
1693
1693
 
1694
1694
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1695
1695
 
1696
1696
  `;return l+d+c}function Bp(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
- ...[truncated ${s.length-e} chars]`:s:"No headers"}var El="You are Claude Code, Anthropic's official CLI for Claude.",cw=["claude-code-20250219","interleaved-thinking-2025-05-14"],eo="2023-06-01",to=64,uw=1024;var Gp=18e4,Up=6e4,Wp={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"},Il={Read:"readfile",Write:"write_file",Edit:"edit_file",Glob:"glob_search",Grep:"search",Bash:"execute_shell",TodoWrite:"todo_write",Task:"task",WebFetch:"web_fetch",WebSearch:"web_search",NotebookEdit:"notebook_edit",AskUserQuestion:"ask_user"},bn=class{client;defaultModel;maxTokens;retryConfig;baseUrl;authToken;isProxyMode;claudeCodeUserId;betaFeatures;systemPromptPrefix;sanitizeToolsForProxy;disableCaching;thinkingConfig=null;constructor(e){this.authToken=e.authToken,this.baseUrl=(e.baseUrl||"https://api.anthropic.com").replace(/\/+$/,"");let t=this.baseUrl.includes("api.anthropic.com");this.isProxyMode=e.forceClaudeCodeMode||!t;let s=typeof e.userId=="string"?e.userId.trim():"";this.claudeCodeUserId=s?this.sanitizeUserId(s):this.generateSafeUserId(),this.betaFeatures=e.betaFeatures||cw,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?El:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=Zv.create({baseURL:this.baseUrl,headers:this.buildHeaders(),timeout:3e5,validateStatus:()=>true}),this.defaultModel=e.defaultModel||"claude-sonnet-4-5-20250929",this.maxTokens=e.maxTokens||32e3;let n=dn("anthropic",this.baseUrl);this.retryConfig=is(void 0,{...n,...e.retry}),this.debugLog("Initialized",{baseUrl:this.baseUrl,isProxyMode:this.isProxyMode,defaultModel:this.defaultModel,betaFeatures:this.betaFeatures});}setThinking(e){this.thinkingConfig=e,this.debugLog("Thinking config updated",{config:e});}setUserId(e){let t=e?.trim?.()||"";t&&(this.claudeCodeUserId=this.sanitizeUserId(t));}isCacheControlError(e){let t="";try{let s=e.response?.data;if(typeof s=="string")t=s.toLowerCase();else if(s&&typeof s=="object"){let n={error:s.error,message:s.message,type:s.type,code:s.code};t=JSON.stringify(n).toLowerCase();}else t=String(e.message||"").toLowerCase();}catch{t=String(e.message||"").toLowerCase();}return t.includes("cache_control")||t.includes("ttl=")||t.includes("ephemeral")||t.includes("cache")&&t.includes("block")}async chat(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.requestMaxRetries,r=null,i=s.disableCaching||false;for(let o=0;o<=n;o++){let l={...s,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);o===0&&this.logRequest(t.model||this.defaultModel,c);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(p.status!==200){let f="";for await(let C of p.data)f+=C.toString();let b=`${this.baseUrl}${d}`,y=Ft(b,this.buildHeaders(),c,!1);m.error("CURL","=== [chat] API Error - Full Request CURL ==="),m.error("CURL",y),m.error("CURL",`=== Error Headers: ${Bp(p.headers)} ===`),m.error("CURL",`=== Error Response: ${f.substring(0,1e3)} ===`);let w=new Error(`Anthropic API error: ${p.status}`);w.response={status:p.status,headers:p.headers,data:f};try{let C=JSON.parse(f);w.response.data=C,C.error?.message?w.message=`Anthropic API error: ${p.status} - ${C.error.message}`:C.message&&(w.message=`Anthropic API error: ${p.status} - ${C.message}`),this.debugLog("API Error Details",C);}catch{this.debugLog("API Error (non-JSON)",{status:p.status,dataLength:f.length});}throw w}let h=await this.collectStreamResponse(p.data),g=Date.now()-u;return ge.llmResponse("anthropic",g,h.usage,h.choices[0]),this.debugLog("Response",{duration:`${g}ms`,usage:h.usage}),h}catch(u){await this.normalizeAxiosStreamError(u),r=u;let d=ft(u);if(d.code==="PROXY_UPSTREAM_FAILED"){let b=JSON.stringify(c||{}).length,y=Array.isArray(e)?e.length:0,w=Array.isArray(e)?e.reduce((C,k)=>k?.content?typeof k.content=="string"?C+k.content.length:Array.isArray(k.content)?C+k.content.map(T=>typeof T.text=="string"?T.text.length:0).reduce((T,_)=>T+_,0):C:C,0):0;m.warn("Anthropic","Upstream request failed (PROXY_UPSTREAM_FAILED)",{attempt:`${o+1}/${n+1}`,payloadSize:b,msgCount:y,promptChars:w,status:u.response?.status});}if(this.debugLog("Error",{message:u.message,category:d.category,code:d.code,attempt:`${o+1}/${n+1}`}),ge.llmError("anthropic",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:o+1}),m.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(!d.retryable||o===n)throw d;let p=Bi(u.response?.headers),h=hr(d.category,o+1,p||d.retryAfter),g=d.category==="retryable_rate_limit",f=g?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${nt(h)} \u540E\u91CD\u8BD5...`:`Retrying in ${nt(h)}...`;this.debugLog("Retrying",{delay:nt(h),attempt:o+1,isRateLimit:g,serverDelay:p?nt(p):"none",retryMsg:f});try{await As(h,s.signal);}catch(b){throw b?.name==="AbortError"&&this.debugLog("Chat retry interrupted by user"),b}}}throw r||new Error("Unknown error during retry")}async collectStreamResponse(e){let t="",s="",n=[],r="",i=null,o="";for await(let c of e){let u=c.toString();t+=u;let d=t.split(`
1697
+ ...[truncated ${s.length-e} chars]`:s:"No headers"}var El="You are Claude Code, Anthropic's official CLI for Claude.",uw=["claude-code-20250219","interleaved-thinking-2025-05-14"],eo="2023-06-01",to=64,dw=1024;var Gp=18e4,Up=6e4,Wp={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"},Il={Read:"readfile",Write:"write_file",Edit:"edit_file",Glob:"glob_search",Grep:"search",Bash:"execute_shell",TodoWrite:"todo_write",Task:"task",WebFetch:"web_fetch",WebSearch:"web_search",NotebookEdit:"notebook_edit",AskUserQuestion:"ask_user"},bn=class{client;defaultModel;maxTokens;retryConfig;baseUrl;authToken;isProxyMode;claudeCodeUserId;betaFeatures;systemPromptPrefix;sanitizeToolsForProxy;disableCaching;thinkingConfig=null;constructor(e){this.authToken=e.authToken,this.baseUrl=(e.baseUrl||"https://api.anthropic.com").replace(/\/+$/,"");let t=this.baseUrl.includes("api.anthropic.com");this.isProxyMode=e.forceClaudeCodeMode||!t;let s=typeof e.userId=="string"?e.userId.trim():"";this.claudeCodeUserId=s?this.sanitizeUserId(s):this.generateSafeUserId(),this.betaFeatures=e.betaFeatures||uw,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?El: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=dn("anthropic",this.baseUrl);this.retryConfig=is(void 0,{...n,...e.retry}),this.debugLog("Initialized",{baseUrl:this.baseUrl,isProxyMode:this.isProxyMode,defaultModel:this.defaultModel,betaFeatures:this.betaFeatures});}setThinking(e){this.thinkingConfig=e,this.debugLog("Thinking config updated",{config:e});}setUserId(e){let t=e?.trim?.()||"";t&&(this.claudeCodeUserId=this.sanitizeUserId(t));}isCacheControlError(e){let t="";try{let s=e.response?.data;if(typeof s=="string")t=s.toLowerCase();else if(s&&typeof s=="object"){let n={error:s.error,message:s.message,type:s.type,code:s.code};t=JSON.stringify(n).toLowerCase();}else t=String(e.message||"").toLowerCase();}catch{t=String(e.message||"").toLowerCase();}return t.includes("cache_control")||t.includes("ttl=")||t.includes("ephemeral")||t.includes("cache")&&t.includes("block")}async chat(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.requestMaxRetries,r=null,i=s.disableCaching||false;for(let o=0;o<=n;o++){let l={...s,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);o===0&&this.logRequest(t.model||this.defaultModel,c);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(p.status!==200){let f="";for await(let C of p.data)f+=C.toString();let b=`${this.baseUrl}${d}`,y=Ft(b,this.buildHeaders(),c,!1);m.error("CURL","=== [chat] API Error - Full Request CURL ==="),m.error("CURL",y),m.error("CURL",`=== Error Headers: ${Bp(p.headers)} ===`),m.error("CURL",`=== Error Response: ${f.substring(0,1e3)} ===`);let w=new Error(`Anthropic API error: ${p.status}`);w.response={status:p.status,headers:p.headers,data:f};try{let C=JSON.parse(f);w.response.data=C,C.error?.message?w.message=`Anthropic API error: ${p.status} - ${C.error.message}`:C.message&&(w.message=`Anthropic API error: ${p.status} - ${C.message}`),this.debugLog("API Error Details",C);}catch{this.debugLog("API Error (non-JSON)",{status:p.status,dataLength:f.length});}throw w}let h=await this.collectStreamResponse(p.data),g=Date.now()-u;return ge.llmResponse("anthropic",g,h.usage,h.choices[0]),this.debugLog("Response",{duration:`${g}ms`,usage:h.usage}),h}catch(u){await this.normalizeAxiosStreamError(u),r=u;let d=ft(u);if(d.code==="PROXY_UPSTREAM_FAILED"){let b=JSON.stringify(c||{}).length,y=Array.isArray(e)?e.length:0,w=Array.isArray(e)?e.reduce((C,k)=>k?.content?typeof k.content=="string"?C+k.content.length:Array.isArray(k.content)?C+k.content.map(T=>typeof T.text=="string"?T.text.length:0).reduce((T,_)=>T+_,0):C:C,0):0;m.warn("Anthropic","Upstream request failed (PROXY_UPSTREAM_FAILED)",{attempt:`${o+1}/${n+1}`,payloadSize:b,msgCount:y,promptChars:w,status:u.response?.status});}if(this.debugLog("Error",{message:u.message,category:d.category,code:d.code,attempt:`${o+1}/${n+1}`}),ge.llmError("anthropic",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:o+1}),m.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(!d.retryable||o===n)throw d;let p=Bi(u.response?.headers),h=hr(d.category,o+1,p||d.retryAfter),g=d.category==="retryable_rate_limit",f=g?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${nt(h)} \u540E\u91CD\u8BD5...`:`Retrying in ${nt(h)}...`;this.debugLog("Retrying",{delay:nt(h),attempt:o+1,isRateLimit:g,serverDelay:p?nt(p):"none",retryMsg:f});try{await As(h,s.signal);}catch(b){throw b?.name==="AbortError"&&this.debugLog("Chat retry interrupted by user"),b}}}throw r||new Error("Unknown error during retry")}async collectStreamResponse(e){let t="",s="",n=[],r="",i=null,o="";for await(let c of e){let u=c.toString();t+=u;let d=t.split(`
1698
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?Il[b.name]||this.fromClaudeCodeToolName(b.name):b.name;n.push({id:b.id,type:"function",function:{name:y,arguments:""}});}break;case "content_block_delta":f.delta?.type==="text_delta"?s+=f.delta.text||"":f.delta?.type==="input_json_delta"?n.length>0&&(n[n.length-1].function.arguments+=f.delta.partial_json||""):f.delta?.type==="thinking_delta"&&(r+=f.delta.thinking||"");break;case "message_delta":f.usage&&(i={...i,...f.usage});break}}catch(f){process.env.CLI_DEBUG==="1"&&m.warn("Anthropic",`Stream parse error: ${f}, data: ${g.substring(0,200)}`);}}}let l=this.buildUsageFromRaw(i);return {id:o,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...r?{reasoning_content:r}:{}},finish_reason:n.length>0?"tool_calls":"stop"}],usage:l}}async*chatStreamed(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.streamMaxRetries,r=0,i=s.disableCaching||false,o=true;for(;;){let l={...s,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);c.stream=true,o&&(this.logRequest(t.model||this.defaultModel,c,true),o=false);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(this.debugLog("Stream started",{status:p.status}),p.status!==200){let v="";for await(let A of p.data)v+=A.toString();let E=`${this.baseUrl}${d}`,L=Ft(E,this.buildHeaders(),c,!1);m.error("CURL","=== [chatStreamed] API Error - Full Request CURL ==="),m.error("CURL",L),m.error("CURL",`=== Error Headers: ${Bp(p.headers)} ===`),m.error("CURL",`=== Error Response: ${v.substring(0,1e3)} ===`);let I=new Error(`Anthropic API error: ${p.status}`);I.response={status:p.status,headers:p.headers,data:v};try{let A=JSON.parse(v);I.response.data=A,A.error?.message?I.message=`Anthropic API error: ${p.status} - ${A.error.message}`:A.message&&(I.message=`Anthropic API error: ${p.status} - ${A.message}`),this.debugLog("API Error Details (stream)",A);}catch{this.debugLog("API Error (non-JSON, stream)",{status:p.status,dataLength:v.length});}throw I}let h="",g=[],f=0,b=!1,y=null,w=!1,C=Date.now(),k=0,T=0,_=null,M=null,F=[],x=null;for await(let v of this.createTimeoutStream(p.data,t.signal)){C=Date.now();let E=v.toString();h+=E;let L=h.split(/\n\n+/);h=L.pop()||"";for(let I of L){let A=I.split(`
1699
1699
  `),O="";for(let $ of A){let P=$.trim();if(P&&!P.startsWith("event:"))if(P.startsWith("data:")){let N=P.slice(5);N.startsWith(" ")&&(N=N.slice(1)),O+=N;}else O+=P;}if(!(!O||O==="[DONE]"))try{let $=O.trim(),P=JSON.parse($);if(process.env.CLI_DEBUG==="1"){let G=JSON.stringify(P).substring(0,80);m.debug("SSE",`${P.type.padEnd(20)} ${G}${JSON.stringify(P).length>80?"...":""}`);}let N=Date.now(),D=this.handleStreamEvent(P,g,f,b,y);if(process.env.CLI_DEBUG==="1"){let G=Date.now()-N;G>50&&m.warn("SSE",`\u26A0\uFE0F Slow event handling: ${P.type} took ${G}ms`);}if(D.yield){let G=Date.now();if(yield D.yield,process.env.CLI_DEBUG==="1"){let q=Date.now()-G;q>100&&m.warn("SSE",`\u26A0\uFE0F Slow yield consumer: ${P.type} yield took ${q}ms`);}}if(D.roleSent!==void 0&&(b=D.roleSent),D.incrementToolIndex&&f++,D.usage&&(y=D.usage),D.error)throw new Error(D.error);D.contentBlockStart&&(T++,D.blockType&&(M=D.blockType)),D.contentBlockStop&&(k++,M==="thinking"&&(yield {choices:[{delta:{reasoning_complete:!0},index:0}]}),M=null),D.messageStop&&(w=!0),D.stopReason&&(_=D.stopReason),P.type==="content_block_start"?P.content_block?.type==="thinking"?x={type:"thinking",thinking:"",signature:""}:P.content_block?.type==="redacted_thinking"&&F.push({type:"redacted_thinking",data:P.content_block.data}):P.type==="content_block_delta"?x&&(P.delta?.type==="thinking_delta"?x.thinking+=P.delta.thinking||"":P.delta?.type==="signature_delta"&&(x.signature+=P.delta.signature||"")):P.type==="content_block_stop"&&x&&(F.push({type:x.type,thinking:x.thinking,signature:x.signature}),x=null);}catch{}}}let R=Date.now()-u;if(this.debugLog("Stream completion check",{messageStopReceived:w,stopReason:_,contentBlocksStarted:T,contentBlocksCompleted:k,toolCallsCount:g.length,duration:`${R}ms`}),!w&&!_){let v=new Error(`Stream incomplete: message_stop not received (blocks: ${T} started, ${k} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:w,stopReason:_,contentBlocksStarted:T,contentBlocksCompleted:k,toolCallsCount:g.length,duration:`${R}ms`}),v}if(T!==k)if(_==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:T,contentBlocksCompleted:k,stopReason:_}),m.warn("Anthropic","\u26A0\uFE0F Response truncated due to max_tokens limit. Consider increasing max_tokens or breaking down the task.");else {let v=new Error(`Stream incomplete: content blocks mismatch (${T} started, ${k} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:T,contentBlocksCompleted:k,stopReason:_}),v}if(g.length>0&&_!=="max_tokens")for(let v of g){let E=v.function?.arguments||"";if(E&&E.trim())try{JSON.parse(E);}catch{let L=new Error(`Stream incomplete: tool arguments truncated for ${v.function?.name}`);throw L.code="STREAM_INCOMPLETE",L.isNetworkInterrupt=!0,L.toolName=v.function?.name,this.debugLog("Tool arguments truncated",{toolName:v.function?.name,argsLength:E.length,argsPreview:E.substring(0,100)}),L}}else if(_==="max_tokens"&&g.length>0){let v=g[g.length-1],E=v?.function?.arguments||"";try{JSON.parse(E);}catch{this.debugLog("Tool arguments truncated due to max_tokens (expected)",{toolName:v?.function?.name,argsLength:E.length}),m.warn("Anthropic",`\u26A0\uFE0F Tool call ${v?.function?.name} arguments truncated due to max_tokens. The tool call will be incomplete.`);}}this.debugLog("finalUsage before build",y);let j=this.buildUsageFromRaw(y);this.debugLog("usage after build",j),!b&&g.length===0&&m.warn("Anthropic",`\u26A0\uFE0F Stream completed with no content! duration: ${R}ms, usage: ${JSON.stringify(y)}`),ge.llmResponse("anthropic-stream",R,j||{},{}),this.debugLog("Stream complete",{duration:`${R}ms`}),yield {choices:[{delta:{},finish_reason:"stop",index:0}],...j?{usage:j}:{},...F.length>0?{thinking_blocks:F}:{}};return}catch(u){await this.normalizeAxiosStreamError(u);let d=ft(u);this.debugLog("Stream error",{message:u.message,category:d.category,retryable:d.retryable});let p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",h=`${this.baseUrl}${p}`,g=Ft(h,this.buildHeaders(),c,false);if(m.error("CURL","=== [chatStreamed catch] Stream Error - Full Request CURL ==="),m.error("CURL",g),m.error("CURL",`=== Error: ${d.message} ===`),ge.llmError("anthropic-stream",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:r+1}),m.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(d.retryable&&r<n){r++;let f=Bi(u.response?.headers),b=hr(d.category,r,f||d.retryAfter),y=d.category==="retryable_rate_limit",w=d.category==="retryable_stream";this.debugLog("Stream retrying",{delay:nt(b),attempt:`${r}/${n}`,isRateLimit:y,isStreamIncomplete:w}),yield {type:"stream_retry",error:d.message,errorCode:d.code,attempt:r,maxRetries:n,delayMs:b,isRateLimit:y,isNetworkError:w};try{await As(b,t.signal);}catch(C){throw C?.name==="AbortError"&&this.debugLog("Stream retry interrupted by user"),C}this.debugLog("Stream retry starting",{attempt:r}),yield {type:"stream_recovered",attempt:r,maxRetries:n};continue}throw d}}}buildPayload(e,t){let s=t.model||this.defaultModel,{system:n,anthropicMessages:r}=this.convertMessages(e,t),i=r,o=[];if(t.disableCaching?(o.push({type:"text",text:El}),n&&o.push({type:"text",text:`
1700
1700
  `+n})):(o.push({type:"text",text:El,cache_control:{type:"ephemeral"}}),n&&o.push({type:"text",text:`
1701
- `+n,cache_control:{type:"ephemeral"}})),process.env.CLI_DEBUG==="1"&&n){let c=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"],u=c.some(h=>n.includes(h)),d=c.reduce((h,g)=>h>=0?h:n.indexOf(g),-1),p=d>=0?n.slice(d,d+300):void 0;m.info("MEMORY_INJECT","Anthropic system memory check",{hasMemory:u,systemLength:n.length,snippet:p});}let l={model:this.normalizeModelName(s),system:o,metadata:this.buildMetadata(t.metadata),max_tokens:this.maxTokens};return (!t.thinking?.type||t.thinking.type==="disabled")&&(l.temperature=t.temperature??.7),l.stream=true,l.messages=i,t.tools?.length&&(l.tools=this.buildToolsPayload(t.tools,t)),t.webSearch?.enabled&&(l.tools=l.tools||[],l.tools.push(this.buildWebSearchTool(t.webSearch))),l.tools?.length>0&&this.ensureLastToolCacheControl(l.tools,t),this.shouldEnableThinking(s,t)&&(l.thinking=this.buildThinkingPayload(t),delete l.temperature,l.temperature=1),this.checkRequestBudget(l),l}checkRequestBudget(e){let s=JSON.stringify(e).length;if(s>Sr){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:Sr,messageCount:e.messages?.length||0}),e.messages){let r=[...e.messages.map((i,o)=>({index:o,role:i.role,contentSize:JSON.stringify(i.content||"").length}))].sort((i,o)=>o.contentSize-i.contentSize);this.debugLog("Largest messages in request",{top5:r.slice(0,5)});}console.warn(`[Anthropic] \u26A0\uFE0F Request body size (${(s/1024/1024).toFixed(2)}MB) exceeds ${(Sr/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>aw&&this.debugLog("Request body approaching limit",{bodySize:s,limit:Sr,percentage:(s/Sr*100).toFixed(1)+"%"});}mergeSystemIntoMessages(e,t){let s=[...t],n=s.findIndex(r=>r.role==="user");if(n>=0){let r=s[n],i={type:"text",text:`<system_context>
1701
+ `+n,cache_control:{type:"ephemeral"}})),process.env.CLI_DEBUG==="1"&&n){let c=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"],u=c.some(h=>n.includes(h)),d=c.reduce((h,g)=>h>=0?h:n.indexOf(g),-1),p=d>=0?n.slice(d,d+300):void 0;m.info("MEMORY_INJECT","Anthropic system memory check",{hasMemory:u,systemLength:n.length,snippet:p});}let l={model:this.normalizeModelName(s),system:o,metadata:this.buildMetadata(t.metadata),max_tokens:this.maxTokens};return (!t.thinking?.type||t.thinking.type==="disabled")&&(l.temperature=t.temperature??.7),l.stream=true,l.messages=i,t.tools?.length&&(l.tools=this.buildToolsPayload(t.tools,t)),t.webSearch?.enabled&&(l.tools=l.tools||[],l.tools.push(this.buildWebSearchTool(t.webSearch))),l.tools?.length>0&&this.ensureLastToolCacheControl(l.tools,t),this.shouldEnableThinking(s,t)&&(l.thinking=this.buildThinkingPayload(t),delete l.temperature,l.temperature=1),this.checkRequestBudget(l),l}checkRequestBudget(e){let s=JSON.stringify(e).length;if(s>Sr){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:Sr,messageCount:e.messages?.length||0}),e.messages){let r=[...e.messages.map((i,o)=>({index:o,role:i.role,contentSize:JSON.stringify(i.content||"").length}))].sort((i,o)=>o.contentSize-i.contentSize);this.debugLog("Largest messages in request",{top5:r.slice(0,5)});}console.warn(`[Anthropic] \u26A0\uFE0F Request body size (${(s/1024/1024).toFixed(2)}MB) exceeds ${(Sr/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>lw&&this.debugLog("Request body approaching limit",{bodySize:s,limit:Sr,percentage:(s/Sr*100).toFixed(1)+"%"});}mergeSystemIntoMessages(e,t){let s=[...t],n=s.findIndex(r=>r.role==="user");if(n>=0){let r=s[n],i={type:"text",text:`<system_context>
1702
1702
  ${e}
1703
- </system_context>`};Array.isArray(r.content)?s[n]={...r,content:[i,...r.content]}:typeof r.content=="string"&&(s[n]={...r,content:[i,{type:"text",text:r.content}]});}return s}buildToolsPayload(e,t){return e.map(n=>{let r=this.transformToolDefinition(n);return t.enableFGTS&&(r.eager_input_streaming=true),r})}ensureLastToolCacheControl(e,t){if(e.length===0||t.disableCaching)return;let s=e[e.length-1];s.cache_control={type:"ephemeral"},this.debugLog("Added cache_control to last tool",{toolName:s.name});}buildWebSearchTool(e){let t={type:"web_search_20250305",name:"web_search"};return e.max_uses&&(t.max_uses=e.max_uses),e.user_location&&(t.user_location=e.user_location),t}buildThinkingPayload(e){let t=e.thinking?.budget_tokens||this.maxTokens-1;return {type:"enabled",budget_tokens:Math.max(t,uw)}}buildMetadata(e){let t={...e};return t.user_id?t.user_id=this.sanitizeUserId(t.user_id):t.user_id=this.claudeCodeUserId,t}shouldEnableThinking(e,t){return t.thinking?.type==="enabled"?true:t.thinking?.type==="disabled"?false:!!(e.endsWith("-thinking")||e.includes("opus-4-6")||e.includes("opus-4.6")||e.includes("opus-4-5")||e.includes("opus-4.5"))}normalizeModelName(e){return e.endsWith("-thinking")?e.replace(/-thinking$/,""):e}convertMessages(e,t){let s=this.normalizeMessages(e),n=[],r=[];for(let u of s){if(u.role==="system"){let p=me(u.content).trim();p&&n.push(p);continue}let d=this.convertSingleMessage(u);d&&r.push(d);}let i=this.mergeConsecutiveUserMessages(r),l=this.validateToolResultPairs(i);return l.length>0&&l[0].role!=="user"&&l.unshift({role:"user",content:[{type:"text",text:"..."}]}),l.length>0&&!t.disableCaching&&this.addMessageCacheControl(l),{system:n.length>0?n.join(`
1703
+ </system_context>`};Array.isArray(r.content)?s[n]={...r,content:[i,...r.content]}:typeof r.content=="string"&&(s[n]={...r,content:[i,{type:"text",text:r.content}]});}return s}buildToolsPayload(e,t){return e.map(n=>{let r=this.transformToolDefinition(n);return t.enableFGTS&&(r.eager_input_streaming=true),r})}ensureLastToolCacheControl(e,t){if(e.length===0||t.disableCaching)return;let s=e[e.length-1];s.cache_control={type:"ephemeral"},this.debugLog("Added cache_control to last tool",{toolName:s.name});}buildWebSearchTool(e){let t={type:"web_search_20250305",name:"web_search"};return e.max_uses&&(t.max_uses=e.max_uses),e.user_location&&(t.user_location=e.user_location),t}buildThinkingPayload(e){let t=e.thinking?.budget_tokens||this.maxTokens-1;return {type:"enabled",budget_tokens:Math.max(t,dw)}}buildMetadata(e){let t={...e};return t.user_id?t.user_id=this.sanitizeUserId(t.user_id):t.user_id=this.claudeCodeUserId,t}shouldEnableThinking(e,t){return t.thinking?.type==="enabled"?true:t.thinking?.type==="disabled"?false:!!(e.endsWith("-thinking")||e.includes("opus-4-6")||e.includes("opus-4.6")||e.includes("opus-4-5")||e.includes("opus-4.5"))}normalizeModelName(e){return e.endsWith("-thinking")?e.replace(/-thinking$/,""):e}convertMessages(e,t){let s=this.normalizeMessages(e),n=[],r=[];for(let u of s){if(u.role==="system"){let p=me(u.content).trim();p&&n.push(p);continue}let d=this.convertSingleMessage(u);d&&r.push(d);}let i=this.mergeConsecutiveUserMessages(r),l=this.validateToolResultPairs(i);return l.length>0&&l[0].role!=="user"&&l.unshift({role:"user",content:[{type:"text",text:"..."}]}),l.length>0&&!t.disableCaching&&this.addMessageCacheControl(l),{system:n.length>0?n.join(`
1704
1704
 
1705
- `):null,anthropicMessages:l}}addMessageCacheControl(e){let t=false;for(let s=e.length-1;s>=0;s--){let n=e[s];if(!(n.role!=="user"||!Array.isArray(n.content))){for(let r=n.content.length-1;r>=0;r--){let i=n.content[r];if(!t&&i.type==="tool_result"){i.cache_control={type:"ephemeral"},t=true,this.debugLog("Added cache_control to tool_result",{tool_use_id:i.tool_use_id});break}}if(t)break}}t||this.addTextBlockCacheControl(e);}addTextBlockCacheControl(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.role==="user"&&Array.isArray(s.content)){for(let n=s.content.length-1;n>=0;n--)if(s.content[n].type==="text"){s.content[n].cache_control={type:"ephemeral"},this.debugLog("Added cache_control to user text block");return}}}}validateToolResultPairs(e){let t=new Set,s=new Set;for(let i of e)if(Array.isArray(i.content))for(let o of i.content)o.type==="tool_use"&&o.id&&t.add(o.id),o.type==="tool_result"&&o.tool_use_id&&s.add(o.tool_use_id);let n=new Set;for(let i of t)s.has(i)&&n.add(i);this.debugLog("Tool pairing analysis",{toolUseCount:t.size,toolResultCount:s.size,pairedCount:n.size,orphanToolUseIds:Array.from(t).filter(i=>!n.has(i)),orphanToolResultIds:Array.from(s).filter(i=>!n.has(i))});let r=[];for(let i of e){if(!Array.isArray(i.content)){r.push(i);continue}let o=i.content.filter(l=>{if(l.type==="tool_use"){let c=n.has(l.id);return c||this.debugLog("Removing orphan tool_use",{id:l.id}),c}if(l.type==="tool_result"){let c=n.has(l.tool_use_id);return c||this.debugLog("Removing orphan tool_result",{tool_use_id:l.tool_use_id}),c}return true});o.length>0?r.push({...i,content:o}):this.debugLog("Skipping empty message after tool pairing filter",{role:i.role});}return r}mergeConsecutiveUserMessages(e){if(e.length===0)return [];let t=[];for(let s of e){let n=t[t.length-1];if(n&&n.role==="user"&&s.role==="user"){let r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}],i=Array.isArray(s.content)?s.content:[{type:"text",text:s.content}];n.content=[...r,...i];}else t.push(s);}return t}convertSingleMessage(e){if(e.role==="tool"){let s=me(e.content),n=lw(s);return s.length!==n.length&&this.debugLog("Tool output truncated",{tool_call_id:e.tool_call_id,original:s.length,truncated:n.length}),{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:n}]}}if(e.role==="assistant"){let s=[],n=false;if(e.thinking_blocks&&e.thinking_blocks.length>0){n=true;for(let i of e.thinking_blocks)if(i.type==="thinking"){let o={type:"thinking",thinking:i.thinking};i.signature!==void 0&&(o.signature=i.signature),s.push(o);}else if(i.type==="redacted_thinking"){let o={type:"redacted_thinking"};i.data!==void 0&&(o.data=i.data),s.push(o);}}let r=me(e.content);if(r){let i=r.trimEnd();s.push({type:"text",text:i||"."});}else n&&(s.push({type:"text",text:"."}),this.debugLog("Added placeholder text after thinking (no text content)"));if(e.tool_calls)for(let i of e.tool_calls){let o=(i.function.arguments||"").trim(),l={};if(o.length>0)try{l=JSON.parse(o);}catch{this.debugLog("Failed to parse tool arguments",{tool:i.function.name});}let c=this.isProxyMode?Wp[i.function.name]||this.toClaudeCodeToolName(i.function.name):i.function.name;s.push({type:"tool_use",id:i.id,name:c,input:l});}if(s.length>0){let i=s[s.length-1];this.debugLog("Assistant message final check",{contentLength:s.length,lastBlockType:i.type,hasThinkingBlocks:n,blockTypes:s.map(o=>o.type),lastBlockTextPreview:i.type==="text"?(i.text||"").substring(0,50):void 0}),i.type==="thinking"||i.type==="redacted_thinking"?(s.push({type:"text",text:"."}),this.debugLog("Fixed: Added text block after thinking")):i.type==="text"&&(!i.text||!i.text.trim())&&s.some(l=>l.type==="thinking"||l.type==="redacted_thinking")&&(i.text=".",this.debugLog("Fixed: Ensured text block has content after thinking"));}return s.length>0?{role:"assistant",content:s}:null}if(Array.isArray(e.content)){let s=e.content.filter(i=>i.type==="text");if(!e.content.some(i=>i.type!=="text")&&s.length===1){let i=s[0].text;return i.trim()?{role:"user",content:i}:null}let r=this.convertMultimodalContent(e.content);return r.length>0?{role:"user",content:r}:null}let t=me(e.content);return t.trim()?{role:"user",content:t}:null}convertMultimodalContent(e){let t=[];for(let s of e)if(s.type==="text")t.push({type:"text",text:s.text});else if(s.type==="image_url"){let n=this.convertImageUrl(s.image_url.url);n&&t.push(n);}return t}convertImageUrl(e){if(e.startsWith("data:")){let t=e.match(/^data:([^;]+);base64,(.+)$/);if(t)return {type:"image",source:{type:"base64",media_type:t[1],data:t[2]}}}else return {type:"image",source:{type:"url",url:e}};return null}normalizeMessages(e){let t=e.filter(s=>{let n=s.role==="assistant"&&!!(s.tool_calls&&s.tool_calls.length>0),r=s.role==="assistant"&&!!(s.thinking_blocks&&s.thinking_blocks.length>0);return n||r?true:s.content?typeof s.content=="string"?s.content.trim().length>0:Array.isArray(s.content)?s.content.length>0:true:false});return t.length===0?[]:(this.validateMessageAlternation(t),t)}validateMessageAlternation(e){let t=e.filter(n=>n.role!=="system"),s=false;for(let n=1;n<t.length;n++)t[n].role===t[n-1].role&&(s=true,this.debugLog("Message alternation warning",{index:n,prevRole:t[n-1].role,currentRole:t[n].role}));!s&&t.length>1&&this.debugLog("Message alternation OK",{messageCount:t.length,roles:t.map(n=>n.role)});}convertResponse(e){this.debugLog("Raw response",e);let t=e.content||[],s="",n=[],r="";for(let o of t)if(o.type==="text")s+=o.text;else if(o.type==="tool_use"){let l=this.isProxyMode?Il[o.name]||this.fromClaudeCodeToolName(o.name):o.name;n.push({id:o.id,type:"function",function:{name:l,arguments:JSON.stringify(o.input)}});}else o.type==="thinking"&&(r=o.thinking||"");let i=this.buildUsageFromRaw(e.usage);return {id:e.id,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...r?{reasoning_content:r}:{}},finish_reason:this.convertStopReason(e.stop_reason)}],usage:i}}buildUsageFromRaw(e){if(!e)return {prompt_tokens:0,completion_tokens:0,total_tokens:0};let t={prompt_tokens:e.input_tokens||0,completion_tokens:e.output_tokens||0,total_tokens:(e.input_tokens||0)+(e.output_tokens||0)};return e.cache_read_input_tokens&&(t.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens&&(t.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(e.cache_creation.ephemeral_5m_input_tokens&&(t.cache_creation_5m_tokens=e.cache_creation.ephemeral_5m_input_tokens),e.cache_creation.ephemeral_1h_input_tokens&&(t.cache_creation_1h_tokens=e.cache_creation.ephemeral_1h_input_tokens)),t}convertStopReason(e){switch(e){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "tool_calls";default:return "stop"}}handleStreamEvent(e,t,s,n,r){switch(e.type){case "message_start":return this.debugLog("message_start usage",e.message?.usage),process.env.CLI_DEBUG==="1"&&e.message&&m.debug("Anthropic",`message_start full: ${JSON.stringify(e.message,null,2)}`),{usage:e.message?.usage,yield:{type:"message_start",message:{id:e.message?.id,model:e.message?.model}}};case "content_block_start":return {...this.handleContentBlockStart(e,t,s,n),contentBlockStart:true};case "content_block_delta":return this.handleContentBlockDelta(e,t);case "content_block_stop":return this.validateToolArguments(t),{contentBlockStop:true};case "message_delta":this.debugLog("message_delta usage",{eventUsage:e.usage,currentUsage:r});let o=e.delta?.stop_reason||e.stop_reason;if(o&&this.debugLog("message_delta stop_reason",o),e.usage&&r){let u={...r,...e.usage};return this.debugLog("merged usage",u),{usage:u,stopReason:o}}return {usage:e.usage||r,stopReason:o};case "message_stop":return this.debugLog("Message stop received"),{messageStop:true};case "ping":return {};case "error":return {error:e.error?.message||"Stream error"};default:let l=e.type?.toLowerCase()||"";if(l==="done"||l==="stream_end"||l==="end")return this.debugLog("Alternative message stop received",{type:e.type}),{messageStop:true};let c=e.stop_reason||e.delta?.stop_reason;return c?(this.debugLog("stop_reason found in unknown event",{type:e.type,stopReason:c}),{stopReason:c}):(this.debugLog("Unknown event type",{type:e.type}),{})}}handleContentBlockStart(e,t,s,n){let r=e.content_block?.type;if(r==="text")return n?{blockType:r}:{yield:{choices:[{delta:{role:"assistant"},index:0}]},roleSent:true,blockType:r};if(r==="tool_use"){let i=e.content_block,o=this.isProxyMode?Il[i.name]||this.fromClaudeCodeToolName(i.name):i.name,l="";return i.input&&typeof i.input=="object"&&Object.keys(i.input).length>0&&(l=JSON.stringify(i.input)),t.push({index:s,id:i.id,type:"function",function:{name:o,arguments:l}}),{yield:{choices:[{delta:{tool_calls:[{index:s,id:i.id,type:"function",function:{name:o}}]},index:0}]},incrementToolIndex:true,blockType:r}}else if(r==="thinking")return {blockType:r};return {blockType:r}}handleContentBlockDelta(e,t){if(e.delta?.type==="text_delta")return {yield:{choices:[{delta:{content:e.delta.text||""},index:0}]}};if(e.delta?.type==="input_json_delta"){let s=e.delta.partial_json||"";if(t.length>0){let n=t[t.length-1];return n.function.arguments+=s,{yield:{choices:[{delta:{tool_calls:[{index:n.index,function:{arguments:s}}]},index:0}]}}}}else {if(e.delta?.type==="thinking_delta")return {yield:{choices:[{delta:{reasoning_content:e.delta.thinking},index:0}]}};if(e.delta?.type==="signature_delta")return {}}return {}}validateToolArguments(e){if(e.length===0)return;let t=e[e.length-1];if(t.function.arguments)try{JSON.parse(t.function.arguments);}catch{let s=this.tryFixJson(t.function.arguments);s?(t.function.arguments=s,this.debugLog("Auto-fixed tool arguments",{tool:t.function.name})):this.debugLog("Invalid tool arguments JSON",{tool:t.function.name});}}tryFixJson(e){let t=e.trim();if(!t.endsWith("}")){t+="}";try{return JSON.parse(t),t}catch{}}t=e.replace(/,\s*$/,""),t.endsWith("}")||(t+="}");try{return JSON.parse(t),t}catch{}let s=0,n=0,r=false,i=false;for(let o of e){if(i){i=false;continue}if(o==="\\"){i=true;continue}if(o==='"'){r=!r;continue}r||(o==="{"?s++:o==="}"?s--:o==="["?n++:o==="]"&&n--);}for(t=e,r&&(t+='"');n>0;)t+="]",n--;for(;s>0;)t+="}",s--;try{return JSON.parse(t),t}catch{return null}}transformToolDefinition(e){let t=this.isProxyMode?Wp[e.name]||this.toClaudeCodeToolName(e.name):e.name;if(this.isProxyMode){let r=this.stripSchemaPropertyDescriptions(e.parameters);return {name:t,description:e.description,input_schema:r}}if(!this.sanitizeToolsForProxy)return {name:t,description:e.description,input_schema:e.parameters};let s=this.truncateDescription(e.description||e.name),n=this.stripSchemaDescriptions(e.parameters);return {name:t,description:s,input_schema:n}}stripSchemaPropertyDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>this.stripSchemaPropertyDescriptions(s));let t={...e};if(t.properties&&typeof t.properties=="object"){let s={};for(let[n,r]of Object.entries(t.properties))if(r&&typeof r=="object"){let i={...r};delete i.description,i.properties&&(i.properties=this.stripSchemaPropertyDescriptions({properties:i.properties}).properties),i.items&&(i.items=this.stripSchemaPropertyDescriptions(i.items)),s[n]=i;}else s[n]=r;t.properties=s;}t.items&&(t.items=this.stripSchemaPropertyDescriptions(t.items));for(let s of ["oneOf","anyOf","allOf"])t[s]&&Array.isArray(t[s])&&(t[s]=t[s].map(n=>this.stripSchemaPropertyDescriptions(n)));return t}toClaudeCodeToolName(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}fromClaudeCodeToolName(e){return e.replace(/["\s/>]+$/g,"").trim().replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}truncateDescription(e){if(!e)return "Utility tool";let t=e.replace(/\s+/g," ").trim();return t?t.length>120?`${t.slice(0,117)}...`:t:"Utility tool"}stripSchemaDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>this.stripSchemaDescriptions(s));let t={...e};if(delete t.description,t.properties&&typeof t.properties=="object"){let s={};for(let[n,r]of Object.entries(t.properties))s[n]=this.stripSchemaDescriptions(r);t.properties=s;}for(let s of ["items","oneOf","anyOf","allOf"])t[s]&&(t[s]=Array.isArray(t[s])?t[s].map(n=>this.stripSchemaDescriptions(n)):this.stripSchemaDescriptions(t[s]));return t}buildHeaders(){return this.isProxyMode?this.buildClaudeCodeHeaders():this.buildOfficialHeaders()}buildOfficialHeaders(){return {"anthropic-api-key":this.authToken,"anthropic-version":eo,"Content-Type":"application/json"}}buildClaudeCodeHeaders(){return {Accept:"application/json","X-Stainless-Retry-Count":"0","X-Stainless-Timeout":"600","X-Stainless-Lang":"js","X-Stainless-Package-Version":"0.70.0","X-Stainless-OS":"MacOS","X-Stainless-Arch":"arm64","X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version,"anthropic-dangerous-direct-browser-access":"true","anthropic-version":eo,"x-app":"cli","User-Agent":"claude-cli/2.0.55 (external, cli)",Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json","anthropic-beta":this.betaFeatures.join(","),"x-stainless-helper-method":"stream","accept-language":"*","sec-fetch-mode":"cors","accept-encoding":"br, gzip, deflate"}}generateSafeUserId(){if(this.isProxyMode){let s=randomBytes(32).toString("hex"),n=this.generateUUID();return `user_${s}_account__session_${n}`}let e=randomBytes(16).toString("hex"),t=randomBytes(4).toString("hex");return `user_${e}_session_${t}`}generateUUID(){let e=randomBytes(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=e.toString("hex");return `${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}sanitizeUserId(e){if(this.isProxyMode){if(/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),s=this.generateUUID();return `user_${t}_account__session_${s}`}if(/^\+?[\d\s-]{10,}$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),s=this.generateUUID();return `user_${t}_account__session_${s}`}return e}return e.length>to?createHash("sha256").update(e).digest("hex").slice(0,to):/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,to):/^\+?[\d\s-]{10,}$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,to):e}async normalizeAxiosStreamError(e){let t=e?.response?.data;if(!(!t||typeof t!="object"||!(typeof t.pipe=="function")))try{let n=await this.readStreamToString(t);try{e.response.data=JSON.parse(n);}catch{e.response.data=n;}}catch{}}readStreamToString(e){return new Promise((t,s)=>{let n=[];e.on("data",r=>{n.push(typeof r=="string"?Buffer.from(r):r);}),e.on("end",()=>t(Buffer.concat(n).toString("utf-8"))),e.on("error",s);})}async*createTimeoutStream(e,t){let s=false,n=Date.now(),r=0,i=e[Symbol.asyncIterator](),o=()=>new Promise(l=>setImmediate(l));for(process.env.CLI_DEBUG==="1"&&m.debug("STREAM","\u{1F30A} Stream processing started");;){if(t?.aborted)throw this.debugLog("Stream aborted by signal"),process.env.CLI_DEBUG==="1"&&m.debug("STREAM",`\u26D4 Stream aborted after ${r} chunks`),e.destroy?.(),new Error("Request aborted");await o();let l=s?Gp:Up,c;try{let u=t?new Promise((h,g)=>{let f=()=>{g(new Error("Request aborted"));};t.aborted?f():t.addEventListener("abort",f,{once:!0});}):null,d=[i.next(),new Promise((h,g)=>{c=setTimeout(()=>{g(new Error(s?`Stream idle timeout: no data for ${Gp/1e3}s`:`Stream first chunk timeout: no response for ${Up/1e3}s`));},l);})];u&&d.push(u);let p=await Promise.race(d);if(c&&clearTimeout(c),p.done){process.env.CLI_DEBUG==="1"&&m.debug("STREAM",`\u2705 Stream completed successfully (${r} chunks, ${Date.now()-n}ms)`);return}s=!0,n=Date.now(),r++,process.env.CLI_DEBUG==="1"&&r%100===0&&m.debug("STREAM",`\u{1F4E6} Processed ${r} chunks`),yield p.value;}catch(u){c&&clearTimeout(c);let d=u.message?.includes("aborted")||u.message==="Request aborted";throw this.debugLog("Stream timeout or abort",{error:u.message,isAbort:d,receivedFirstChunk:s,idleTime:`${(Date.now()-n)/1e3}s`}),e.destroy?.(),d?(u.name="AbortError",u.code="ERR_CANCELED",u.category="canceled",u):(u.code="STREAM_TIMEOUT",u.isNetworkInterrupt=true,u)}}}debugLog(e,t){process.env.CLI_DEBUG==="1"&&m.debug("Anthropic",t?`${e} ${JSON.stringify(t,null,2)}`:e);}logRequest(e,t,s=false){process.env.CLI_DEBUG_PAYLOAD==="1"&&this.debugLog("Full payload",JSON.stringify(t,null,2));let n=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",r=`${this.baseUrl}${n}`,i=this.buildHeaders();Zo(r,i,t);let o=this.isProxyMode?{Authorization:"Bearer ***","anthropic-version":eo,"anthropic-beta":this.betaFeatures.join(","),"Content-Type":"application/json"}:{"anthropic-api-key":"***","anthropic-version":eo,"Content-Type":"application/json"};ge.llmRequest(s?"anthropic-stream":"anthropic",e,t,r,o),this.debugLog(`${s?"Stream ":""}Request`,{url:r,model:e,isProxyMode:this.isProxyMode});}};W();var so=class extends Lt{constraints;promptBuilder;provider;defaultModel;disableCaching;constructor(e){super(),this.constraints=new wr,this.promptBuilder=new Cr,this.defaultModel=e.defaultModel||"claude-3-5-sonnet-20241022",this.disableCaching=e.disableCaching||false;let{authToken:t,baseUrl:s,defaultModel:n,maxTokens:r,disableCaching:i,userId:o,...l}=e;this.provider=new bn({authToken:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:r,disableCaching:this.disableCaching,userId:o,...l});}prepareRequest(e,t){let s=t.model||this.defaultModel,n=super.prepareRequest(e,{...t,model:s}),r={...n.options};if(r.maxInputTokens!==void 0&&(r.max_tokens=r.maxInputTokens,delete r.maxInputTokens),!r.max_tokens){let i=this.constraints.getTokenLimits(s);r.max_tokens=Math.min(4096,i.maxOutput);}if(!this.disableCaching&&this.constraints.supportsPromptCaching(s)){let i=n.messages[0]?.content?.length||0,o=this.promptBuilder.getCachingRecommendation(i);o.shouldUseCache&&(r.enableCaching=true,r.cacheTtl=o.cacheTTL);}return {...n,options:r}}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("AnthropicAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("AnthropicAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal,enableFGTS:s.options.enableFGTS});}getProvider(){return this.provider}getModelCapabilities(e){let t=e||this.defaultModel;return {supportsVision:this.constraints.supportsVision(t),supportsTools:this.constraints.supportsTools(t),supportsThinking:this.constraints.supportsThinking?.(t)||false,supportsPromptCaching:this.constraints.supportsPromptCaching(t),tokenLimits:this.constraints.getTokenLimits(t)}}getCachingRecommendation(e){return this.promptBuilder.getCachingRecommendation(e)}};var no=class extends Is{getConstraints(){let e=super.getConstraints(),t={...e.validators??{}};t.temperature=Ve(0,1);let s=t.tool_choice;t.tool_choice=r=>r==="required"?"tool_choice=required is not supported by Kimi API":typeof s=="function"?s(r):true;let n=t.n;return t.n=(r,i)=>{let o=typeof n=="function"?n(r,i):true;if(o!==true)return o;let l=i?.temperature??1,c=typeof l=="number"?l:Number(l),u=typeof r=="number"?r:Number(r);return !Number.isNaN(c)&&c<=.001&&u>1?"temperature <= 0.001 requires n=1 for Kimi API":true},{...e,validators:t}}};W();var ro=class extends Lt{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new no,this.promptBuilder=new Ps,this.defaultModel=e.defaultModel||"kimi-k2-0905-preview";let{apiKey:t,baseUrl:s,defaultModel:n,maxTokens:r,maxInputTokens:i,...o}=e;this.provider=new Vt({apiKey:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:r,maxInputTokens:i,...o,structuredOutputMode:"json_object"});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("KimiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("KimiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,signal:t.signal});}getProvider(){return this.provider}};var io=class extends us{getConstraints(){return {maxOutputTokens:{},maxInputTokens:{},supportedParams:new Set(["model","messages","stream","max_tokens","temperature","topP","topK","stopSequences","tools","structuredOutput","signal"]),validators:{temperature:Ve(0,2),topP:Ve(0,1),topK:Ve(1,128),max_tokens:e=>{let t=Number(e);return Number.isNaN(t)?"Must be a number":t<1?"Must be at least 1":true},stopSequences:e=>Array.isArray(e)?e.some(s=>typeof s!="string"||s.length===0)?"All stop sequences must be non-empty strings":true:"Must be an array of strings",stream:Np("boolean")},defaults:{temperature:1}}}};var xr=class extends ds{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:r}=e,i=[];return i.push({content:this.getCoreInstructions(s,n),order:0}),i.push(this.getWorkingDirectorySection(t,s)),i.push({content:this.getCapabilitiesSection(s,n),order:20}),i.push({title:s==="zh"?"\u53C2\u6570\u7EA6\u675F":"Parameter Constraints",content:this.getConstraintInstructions(s),order:30}),i.push({title:s==="zh"?"\u5DE5\u5177\u8C03\u7528":"Tool Usage",content:this.getToolUseInstructions(s),order:40}),i.push({content:this.getGeneralRules(s),order:50}),r&&r.trim()&&i.push({title:s==="zh"?"\u81EA\u5B9A\u4E49\u6307\u4EE4":"Custom Instructions",content:r.trim(),order:60}),Ms(this.combinePromptSections(i))}getConstraintInstructions(e){return e==="zh"?`- temperature: 0.0 - 2.0
1705
+ `):null,anthropicMessages:l}}addMessageCacheControl(e){let t=false;for(let s=e.length-1;s>=0;s--){let n=e[s];if(!(n.role!=="user"||!Array.isArray(n.content))){for(let r=n.content.length-1;r>=0;r--){let i=n.content[r];if(!t&&i.type==="tool_result"){i.cache_control={type:"ephemeral"},t=true,this.debugLog("Added cache_control to tool_result",{tool_use_id:i.tool_use_id});break}}if(t)break}}t||this.addTextBlockCacheControl(e);}addTextBlockCacheControl(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.role==="user"&&Array.isArray(s.content)){for(let n=s.content.length-1;n>=0;n--)if(s.content[n].type==="text"){s.content[n].cache_control={type:"ephemeral"},this.debugLog("Added cache_control to user text block");return}}}}validateToolResultPairs(e){let t=new Set,s=new Set;for(let i of e)if(Array.isArray(i.content))for(let o of i.content)o.type==="tool_use"&&o.id&&t.add(o.id),o.type==="tool_result"&&o.tool_use_id&&s.add(o.tool_use_id);let n=new Set;for(let i of t)s.has(i)&&n.add(i);this.debugLog("Tool pairing analysis",{toolUseCount:t.size,toolResultCount:s.size,pairedCount:n.size,orphanToolUseIds:Array.from(t).filter(i=>!n.has(i)),orphanToolResultIds:Array.from(s).filter(i=>!n.has(i))});let r=[];for(let i of e){if(!Array.isArray(i.content)){r.push(i);continue}let o=i.content.filter(l=>{if(l.type==="tool_use"){let c=n.has(l.id);return c||this.debugLog("Removing orphan tool_use",{id:l.id}),c}if(l.type==="tool_result"){let c=n.has(l.tool_use_id);return c||this.debugLog("Removing orphan tool_result",{tool_use_id:l.tool_use_id}),c}return true});o.length>0?r.push({...i,content:o}):this.debugLog("Skipping empty message after tool pairing filter",{role:i.role});}return r}mergeConsecutiveUserMessages(e){if(e.length===0)return [];let t=[];for(let s of e){let n=t[t.length-1];if(n&&n.role==="user"&&s.role==="user"){let r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}],i=Array.isArray(s.content)?s.content:[{type:"text",text:s.content}];n.content=[...r,...i];}else t.push(s);}return t}convertSingleMessage(e){if(e.role==="tool"){let s=me(e.content),n=cw(s);return s.length!==n.length&&this.debugLog("Tool output truncated",{tool_call_id:e.tool_call_id,original:s.length,truncated:n.length}),{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:n}]}}if(e.role==="assistant"){let s=[],n=false;if(e.thinking_blocks&&e.thinking_blocks.length>0){n=true;for(let i of e.thinking_blocks)if(i.type==="thinking"){let o={type:"thinking",thinking:i.thinking};i.signature!==void 0&&(o.signature=i.signature),s.push(o);}else if(i.type==="redacted_thinking"){let o={type:"redacted_thinking"};i.data!==void 0&&(o.data=i.data),s.push(o);}}let r=me(e.content);if(r){let i=r.trimEnd();s.push({type:"text",text:i||"."});}else n&&(s.push({type:"text",text:"."}),this.debugLog("Added placeholder text after thinking (no text content)"));if(e.tool_calls)for(let i of e.tool_calls){let o=(i.function.arguments||"").trim(),l={};if(o.length>0)try{l=JSON.parse(o);}catch{this.debugLog("Failed to parse tool arguments",{tool:i.function.name});}let c=this.isProxyMode?Wp[i.function.name]||this.toClaudeCodeToolName(i.function.name):i.function.name;s.push({type:"tool_use",id:i.id,name:c,input:l});}if(s.length>0){let i=s[s.length-1];this.debugLog("Assistant message final check",{contentLength:s.length,lastBlockType:i.type,hasThinkingBlocks:n,blockTypes:s.map(o=>o.type),lastBlockTextPreview:i.type==="text"?(i.text||"").substring(0,50):void 0}),i.type==="thinking"||i.type==="redacted_thinking"?(s.push({type:"text",text:"."}),this.debugLog("Fixed: Added text block after thinking")):i.type==="text"&&(!i.text||!i.text.trim())&&s.some(l=>l.type==="thinking"||l.type==="redacted_thinking")&&(i.text=".",this.debugLog("Fixed: Ensured text block has content after thinking"));}return s.length>0?{role:"assistant",content:s}:null}if(Array.isArray(e.content)){let s=e.content.filter(i=>i.type==="text");if(!e.content.some(i=>i.type!=="text")&&s.length===1){let i=s[0].text;return i.trim()?{role:"user",content:i}:null}let r=this.convertMultimodalContent(e.content);return r.length>0?{role:"user",content:r}:null}let t=me(e.content);return t.trim()?{role:"user",content:t}:null}convertMultimodalContent(e){let t=[];for(let s of e)if(s.type==="text")t.push({type:"text",text:s.text});else if(s.type==="image_url"){let n=this.convertImageUrl(s.image_url.url);n&&t.push(n);}return t}convertImageUrl(e){if(e.startsWith("data:")){let t=e.match(/^data:([^;]+);base64,(.+)$/);if(t)return {type:"image",source:{type:"base64",media_type:t[1],data:t[2]}}}else return {type:"image",source:{type:"url",url:e}};return null}normalizeMessages(e){let t=e.filter(s=>{let n=s.role==="assistant"&&!!(s.tool_calls&&s.tool_calls.length>0),r=s.role==="assistant"&&!!(s.thinking_blocks&&s.thinking_blocks.length>0);return n||r?true:s.content?typeof s.content=="string"?s.content.trim().length>0:Array.isArray(s.content)?s.content.length>0:true:false});return t.length===0?[]:(this.validateMessageAlternation(t),t)}validateMessageAlternation(e){let t=e.filter(n=>n.role!=="system"),s=false;for(let n=1;n<t.length;n++)t[n].role===t[n-1].role&&(s=true,this.debugLog("Message alternation warning",{index:n,prevRole:t[n-1].role,currentRole:t[n].role}));!s&&t.length>1&&this.debugLog("Message alternation OK",{messageCount:t.length,roles:t.map(n=>n.role)});}convertResponse(e){this.debugLog("Raw response",e);let t=e.content||[],s="",n=[],r="";for(let o of t)if(o.type==="text")s+=o.text;else if(o.type==="tool_use"){let l=this.isProxyMode?Il[o.name]||this.fromClaudeCodeToolName(o.name):o.name;n.push({id:o.id,type:"function",function:{name:l,arguments:JSON.stringify(o.input)}});}else o.type==="thinking"&&(r=o.thinking||"");let i=this.buildUsageFromRaw(e.usage);return {id:e.id,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...r?{reasoning_content:r}:{}},finish_reason:this.convertStopReason(e.stop_reason)}],usage:i}}buildUsageFromRaw(e){if(!e)return {prompt_tokens:0,completion_tokens:0,total_tokens:0};let t={prompt_tokens:e.input_tokens||0,completion_tokens:e.output_tokens||0,total_tokens:(e.input_tokens||0)+(e.output_tokens||0)};return e.cache_read_input_tokens&&(t.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens&&(t.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(e.cache_creation.ephemeral_5m_input_tokens&&(t.cache_creation_5m_tokens=e.cache_creation.ephemeral_5m_input_tokens),e.cache_creation.ephemeral_1h_input_tokens&&(t.cache_creation_1h_tokens=e.cache_creation.ephemeral_1h_input_tokens)),t}convertStopReason(e){switch(e){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "tool_calls";default:return "stop"}}handleStreamEvent(e,t,s,n,r){switch(e.type){case "message_start":return this.debugLog("message_start usage",e.message?.usage),process.env.CLI_DEBUG==="1"&&e.message&&m.debug("Anthropic",`message_start full: ${JSON.stringify(e.message,null,2)}`),{usage:e.message?.usage,yield:{type:"message_start",message:{id:e.message?.id,model:e.message?.model}}};case "content_block_start":return {...this.handleContentBlockStart(e,t,s,n),contentBlockStart:true};case "content_block_delta":return this.handleContentBlockDelta(e,t);case "content_block_stop":return this.validateToolArguments(t),{contentBlockStop:true};case "message_delta":this.debugLog("message_delta usage",{eventUsage:e.usage,currentUsage:r});let o=e.delta?.stop_reason||e.stop_reason;if(o&&this.debugLog("message_delta stop_reason",o),e.usage&&r){let u={...r,...e.usage};return this.debugLog("merged usage",u),{usage:u,stopReason:o}}return {usage:e.usage||r,stopReason:o};case "message_stop":return this.debugLog("Message stop received"),{messageStop:true};case "ping":return {};case "error":return {error:e.error?.message||"Stream error"};default:let l=e.type?.toLowerCase()||"";if(l==="done"||l==="stream_end"||l==="end")return this.debugLog("Alternative message stop received",{type:e.type}),{messageStop:true};let c=e.stop_reason||e.delta?.stop_reason;return c?(this.debugLog("stop_reason found in unknown event",{type:e.type,stopReason:c}),{stopReason:c}):(this.debugLog("Unknown event type",{type:e.type}),{})}}handleContentBlockStart(e,t,s,n){let r=e.content_block?.type;if(r==="text")return n?{blockType:r}:{yield:{choices:[{delta:{role:"assistant"},index:0}]},roleSent:true,blockType:r};if(r==="tool_use"){let i=e.content_block,o=this.isProxyMode?Il[i.name]||this.fromClaudeCodeToolName(i.name):i.name,l="";return i.input&&typeof i.input=="object"&&Object.keys(i.input).length>0&&(l=JSON.stringify(i.input)),t.push({index:s,id:i.id,type:"function",function:{name:o,arguments:l}}),{yield:{choices:[{delta:{tool_calls:[{index:s,id:i.id,type:"function",function:{name:o}}]},index:0}]},incrementToolIndex:true,blockType:r}}else if(r==="thinking")return {blockType:r};return {blockType:r}}handleContentBlockDelta(e,t){if(e.delta?.type==="text_delta")return {yield:{choices:[{delta:{content:e.delta.text||""},index:0}]}};if(e.delta?.type==="input_json_delta"){let s=e.delta.partial_json||"";if(t.length>0){let n=t[t.length-1];return n.function.arguments+=s,{yield:{choices:[{delta:{tool_calls:[{index:n.index,function:{arguments:s}}]},index:0}]}}}}else {if(e.delta?.type==="thinking_delta")return {yield:{choices:[{delta:{reasoning_content:e.delta.thinking},index:0}]}};if(e.delta?.type==="signature_delta")return {}}return {}}validateToolArguments(e){if(e.length===0)return;let t=e[e.length-1];if(t.function.arguments)try{JSON.parse(t.function.arguments);}catch{let s=this.tryFixJson(t.function.arguments);s?(t.function.arguments=s,this.debugLog("Auto-fixed tool arguments",{tool:t.function.name})):this.debugLog("Invalid tool arguments JSON",{tool:t.function.name});}}tryFixJson(e){let t=e.trim();if(!t.endsWith("}")){t+="}";try{return JSON.parse(t),t}catch{}}t=e.replace(/,\s*$/,""),t.endsWith("}")||(t+="}");try{return JSON.parse(t),t}catch{}let s=0,n=0,r=false,i=false;for(let o of e){if(i){i=false;continue}if(o==="\\"){i=true;continue}if(o==='"'){r=!r;continue}r||(o==="{"?s++:o==="}"?s--:o==="["?n++:o==="]"&&n--);}for(t=e,r&&(t+='"');n>0;)t+="]",n--;for(;s>0;)t+="}",s--;try{return JSON.parse(t),t}catch{return null}}transformToolDefinition(e){let t=this.isProxyMode?Wp[e.name]||this.toClaudeCodeToolName(e.name):e.name;if(this.isProxyMode){let r=this.stripSchemaPropertyDescriptions(e.parameters);return {name:t,description:e.description,input_schema:r}}if(!this.sanitizeToolsForProxy)return {name:t,description:e.description,input_schema:e.parameters};let s=this.truncateDescription(e.description||e.name),n=this.stripSchemaDescriptions(e.parameters);return {name:t,description:s,input_schema:n}}stripSchemaPropertyDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>this.stripSchemaPropertyDescriptions(s));let t={...e};if(t.properties&&typeof t.properties=="object"){let s={};for(let[n,r]of Object.entries(t.properties))if(r&&typeof r=="object"){let i={...r};delete i.description,i.properties&&(i.properties=this.stripSchemaPropertyDescriptions({properties:i.properties}).properties),i.items&&(i.items=this.stripSchemaPropertyDescriptions(i.items)),s[n]=i;}else s[n]=r;t.properties=s;}t.items&&(t.items=this.stripSchemaPropertyDescriptions(t.items));for(let s of ["oneOf","anyOf","allOf"])t[s]&&Array.isArray(t[s])&&(t[s]=t[s].map(n=>this.stripSchemaPropertyDescriptions(n)));return t}toClaudeCodeToolName(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}fromClaudeCodeToolName(e){return e.replace(/["\s/>]+$/g,"").trim().replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}truncateDescription(e){if(!e)return "Utility tool";let t=e.replace(/\s+/g," ").trim();return t?t.length>120?`${t.slice(0,117)}...`:t:"Utility tool"}stripSchemaDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>this.stripSchemaDescriptions(s));let t={...e};if(delete t.description,t.properties&&typeof t.properties=="object"){let s={};for(let[n,r]of Object.entries(t.properties))s[n]=this.stripSchemaDescriptions(r);t.properties=s;}for(let s of ["items","oneOf","anyOf","allOf"])t[s]&&(t[s]=Array.isArray(t[s])?t[s].map(n=>this.stripSchemaDescriptions(n)):this.stripSchemaDescriptions(t[s]));return t}buildHeaders(){return this.isProxyMode?this.buildClaudeCodeHeaders():this.buildOfficialHeaders()}buildOfficialHeaders(){return {"anthropic-api-key":this.authToken,"anthropic-version":eo,"Content-Type":"application/json"}}buildClaudeCodeHeaders(){return {Accept:"application/json","X-Stainless-Retry-Count":"0","X-Stainless-Timeout":"600","X-Stainless-Lang":"js","X-Stainless-Package-Version":"0.70.0","X-Stainless-OS":"MacOS","X-Stainless-Arch":"arm64","X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version,"anthropic-dangerous-direct-browser-access":"true","anthropic-version":eo,"x-app":"cli","User-Agent":"claude-cli/2.0.55 (external, cli)",Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json","anthropic-beta":this.betaFeatures.join(","),"x-stainless-helper-method":"stream","accept-language":"*","sec-fetch-mode":"cors","accept-encoding":"br, gzip, deflate"}}generateSafeUserId(){if(this.isProxyMode){let s=randomBytes(32).toString("hex"),n=this.generateUUID();return `user_${s}_account__session_${n}`}let e=randomBytes(16).toString("hex"),t=randomBytes(4).toString("hex");return `user_${e}_session_${t}`}generateUUID(){let e=randomBytes(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=e.toString("hex");return `${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}sanitizeUserId(e){if(this.isProxyMode){if(/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),s=this.generateUUID();return `user_${t}_account__session_${s}`}if(/^\+?[\d\s-]{10,}$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),s=this.generateUUID();return `user_${t}_account__session_${s}`}return e}return e.length>to?createHash("sha256").update(e).digest("hex").slice(0,to):/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,to):/^\+?[\d\s-]{10,}$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,to):e}async normalizeAxiosStreamError(e){let t=e?.response?.data;if(!(!t||typeof t!="object"||!(typeof t.pipe=="function")))try{let n=await this.readStreamToString(t);try{e.response.data=JSON.parse(n);}catch{e.response.data=n;}}catch{}}readStreamToString(e){return new Promise((t,s)=>{let n=[];e.on("data",r=>{n.push(typeof r=="string"?Buffer.from(r):r);}),e.on("end",()=>t(Buffer.concat(n).toString("utf-8"))),e.on("error",s);})}async*createTimeoutStream(e,t){let s=false,n=Date.now(),r=0,i=e[Symbol.asyncIterator](),o=()=>new Promise(l=>setImmediate(l));for(process.env.CLI_DEBUG==="1"&&m.debug("STREAM","\u{1F30A} Stream processing started");;){if(t?.aborted)throw this.debugLog("Stream aborted by signal"),process.env.CLI_DEBUG==="1"&&m.debug("STREAM",`\u26D4 Stream aborted after ${r} chunks`),e.destroy?.(),new Error("Request aborted");await o();let l=s?Gp:Up,c;try{let u=t?new Promise((h,g)=>{let f=()=>{g(new Error("Request aborted"));};t.aborted?f():t.addEventListener("abort",f,{once:!0});}):null,d=[i.next(),new Promise((h,g)=>{c=setTimeout(()=>{g(new Error(s?`Stream idle timeout: no data for ${Gp/1e3}s`:`Stream first chunk timeout: no response for ${Up/1e3}s`));},l);})];u&&d.push(u);let p=await Promise.race(d);if(c&&clearTimeout(c),p.done){process.env.CLI_DEBUG==="1"&&m.debug("STREAM",`\u2705 Stream completed successfully (${r} chunks, ${Date.now()-n}ms)`);return}s=!0,n=Date.now(),r++,process.env.CLI_DEBUG==="1"&&r%100===0&&m.debug("STREAM",`\u{1F4E6} Processed ${r} chunks`),yield p.value;}catch(u){c&&clearTimeout(c);let d=u.message?.includes("aborted")||u.message==="Request aborted";throw this.debugLog("Stream timeout or abort",{error:u.message,isAbort:d,receivedFirstChunk:s,idleTime:`${(Date.now()-n)/1e3}s`}),e.destroy?.(),d?(u.name="AbortError",u.code="ERR_CANCELED",u.category="canceled",u):(u.code="STREAM_TIMEOUT",u.isNetworkInterrupt=true,u)}}}debugLog(e,t){process.env.CLI_DEBUG==="1"&&m.debug("Anthropic",t?`${e} ${JSON.stringify(t,null,2)}`:e);}logRequest(e,t,s=false){process.env.CLI_DEBUG_PAYLOAD==="1"&&this.debugLog("Full payload",JSON.stringify(t,null,2));let n=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",r=`${this.baseUrl}${n}`,i=this.buildHeaders();Zo(r,i,t);let o=this.isProxyMode?{Authorization:"Bearer ***","anthropic-version":eo,"anthropic-beta":this.betaFeatures.join(","),"Content-Type":"application/json"}:{"anthropic-api-key":"***","anthropic-version":eo,"Content-Type":"application/json"};ge.llmRequest(s?"anthropic-stream":"anthropic",e,t,r,o),this.debugLog(`${s?"Stream ":""}Request`,{url:r,model:e,isProxyMode:this.isProxyMode});}};W();var so=class extends Lt{constraints;promptBuilder;provider;defaultModel;disableCaching;constructor(e){super(),this.constraints=new wr,this.promptBuilder=new Cr,this.defaultModel=e.defaultModel||"claude-3-5-sonnet-20241022",this.disableCaching=e.disableCaching||false;let{authToken:t,baseUrl:s,defaultModel:n,maxTokens:r,disableCaching:i,userId:o,...l}=e;this.provider=new bn({authToken:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:r,disableCaching:this.disableCaching,userId:o,...l});}prepareRequest(e,t){let s=t.model||this.defaultModel,n=super.prepareRequest(e,{...t,model:s}),r={...n.options};if(r.maxInputTokens!==void 0&&(r.max_tokens=r.maxInputTokens,delete r.maxInputTokens),!r.max_tokens){let i=this.constraints.getTokenLimits(s);r.max_tokens=Math.min(4096,i.maxOutput);}if(!this.disableCaching&&this.constraints.supportsPromptCaching(s)){let i=n.messages[0]?.content?.length||0,o=this.promptBuilder.getCachingRecommendation(i);o.shouldUseCache&&(r.enableCaching=true,r.cacheTtl=o.cacheTTL);}return {...n,options:r}}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("AnthropicAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("AnthropicAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal,enableFGTS:s.options.enableFGTS});}getProvider(){return this.provider}getModelCapabilities(e){let t=e||this.defaultModel;return {supportsVision:this.constraints.supportsVision(t),supportsTools:this.constraints.supportsTools(t),supportsThinking:this.constraints.supportsThinking?.(t)||false,supportsPromptCaching:this.constraints.supportsPromptCaching(t),tokenLimits:this.constraints.getTokenLimits(t)}}getCachingRecommendation(e){return this.promptBuilder.getCachingRecommendation(e)}};var no=class extends Is{getConstraints(){let e=super.getConstraints(),t={...e.validators??{}};t.temperature=Ve(0,1);let s=t.tool_choice;t.tool_choice=r=>r==="required"?"tool_choice=required is not supported by Kimi API":typeof s=="function"?s(r):true;let n=t.n;return t.n=(r,i)=>{let o=typeof n=="function"?n(r,i):true;if(o!==true)return o;let l=i?.temperature??1,c=typeof l=="number"?l:Number(l),u=typeof r=="number"?r:Number(r);return !Number.isNaN(c)&&c<=.001&&u>1?"temperature <= 0.001 requires n=1 for Kimi API":true},{...e,validators:t}}};W();var ro=class extends Lt{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new no,this.promptBuilder=new Ps,this.defaultModel=e.defaultModel||"kimi-k2-0905-preview";let{apiKey:t,baseUrl:s,defaultModel:n,maxTokens:r,maxInputTokens:i,...o}=e;this.provider=new Vt({apiKey:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:r,maxInputTokens:i,...o,structuredOutputMode:"json_object"});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("KimiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("KimiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,signal:t.signal});}getProvider(){return this.provider}};var io=class extends us{getConstraints(){return {maxOutputTokens:{},maxInputTokens:{},supportedParams:new Set(["model","messages","stream","max_tokens","temperature","topP","topK","stopSequences","tools","structuredOutput","signal"]),validators:{temperature:Ve(0,2),topP:Ve(0,1),topK:Ve(1,128),max_tokens:e=>{let t=Number(e);return Number.isNaN(t)?"Must be a number":t<1?"Must be at least 1":true},stopSequences:e=>Array.isArray(e)?e.some(s=>typeof s!="string"||s.length===0)?"All stop sequences must be non-empty strings":true:"Must be an array of strings",stream:Np("boolean")},defaults:{temperature:1}}}};var xr=class extends ds{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:r}=e,i=[];return i.push({content:this.getCoreInstructions(s,n),order:0}),i.push(this.getWorkingDirectorySection(t,s)),i.push({content:this.getCapabilitiesSection(s,n),order:20}),i.push({title:s==="zh"?"\u53C2\u6570\u7EA6\u675F":"Parameter Constraints",content:this.getConstraintInstructions(s),order:30}),i.push({title:s==="zh"?"\u5DE5\u5177\u8C03\u7528":"Tool Usage",content:this.getToolUseInstructions(s),order:40}),i.push({content:this.getGeneralRules(s),order:50}),r&&r.trim()&&i.push({title:s==="zh"?"\u81EA\u5B9A\u4E49\u6307\u4EE4":"Custom Instructions",content:r.trim(),order:60}),Ms(this.combinePromptSections(i))}getConstraintInstructions(e){return e==="zh"?`- temperature: 0.0 - 2.0
1706
1706
  - topP: 0.0 - 1.0
1707
1707
  - topK: >= 1
1708
1708
  - maxOutputTokens: \u63A7\u5236\u8F93\u51FA\u957F\u5EA6
@@ -1746,24 +1746,24 @@ Your primary responsibilities:
1746
1746
  1. **Accuracy first**: ensure correctness
1747
1747
  2. **Be concise**: avoid redundancy
1748
1748
  3. **Safety first**: avoid destructive actions
1749
- 4. **Professional tone**: objective and technical`}getModelDisplayName(e){return e?e.includes("gemini-3")?"Gemini 3":e.includes("gemini-2.5")?"Gemini 2.5":e.includes("gemini-2.0")?"Gemini 2.0":e.includes("gemini-1.5")?"Gemini 1.5":e.includes("gemini-1.0")?"Gemini 1.0":e:"Gemini"}supportsVision(e){return e?e.includes("vision")?true:this.isModelType(e,"gemini-1.5*","gemini-2*","gemini-3*"):false}};W();function mw(a){let e="/v1beta/models";if(!a)return e;let t=a.trim();if(!t)return e;let s=t.startsWith("/")?t:`/${t}`;return s=s.replace(/\/+$/,""),s.includes("/models")||(s=`${s}/models`),s}function gw(a){try{let e=JSON.parse(a);return e&&typeof e=="object"?e:{value:e}}catch{return {}}}function zp(a){if(a==null)return "{}";if(typeof a=="string"){let e=a.trim();return e?e.startsWith("{")||e.startsWith("[")?e:JSON.stringify({value:e}):"{}"}try{return JSON.stringify(a)}catch{return "{}"}}var hw="skip_thought_signature_validator",Hp=8192;function Jp(a){return a.includes("gemini-3")||a.includes("preview")}function fw(a){let e=-1;for(let s=a.length-1;s>=0;s--){let n=a[s];if(n.role==="user"&&n.parts?.some(r=>r.text)){e=s;break}}if(e===-1)return a;let t=a.slice();for(let s=e;s<t.length;s++){let n=t[s];if(n.role==="model"&&n.parts){let r=n.parts.slice();for(let i=0;i<r.length;i++){let o=r[i];if(o.functionCall){o.thoughtSignature||(r[i]={...o,thoughtSignature:hw},t[s]={...n,parts:r});break}}}}return t}var vn=class{client;apiKey;baseURL;pathPrefix;userId;retryConfig;authMode;thinkingSettings=null;constructor(e,t="https://generativelanguage.googleapis.com",s,n){this.apiKey=e,this.baseURL=t.replace(/\/$/,""),this.pathPrefix=mw(n?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(n?.authMode),this.retryConfig=is(dn("gemini"),s);let r={"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${In__default.platform()}; ${In__default.arch()})`,"x-goog-api-client":"google-genai-sdk/1.30.0 gl-node/v22.16.0","x-gemini-api-privileged-user-id":this.userId};this.authMode==="header"?r["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(r.Authorization=`Bearer ${this.apiKey}`),this.client=Zv.create({baseURL:this.baseURL,timeout:6e5,headers:r});}resolveAuthMode(e){if(e&&e!=="auto")return e;let t=this.baseURL.includes("generativelanguage.googleapis.com"),s=this.apiKey.startsWith("AIza");return t||s?"query":"bearer"}setThinking(e){this.thinkingSettings=e,process.env.CLI_DEBUG==="1"&&ye("GEMINI","Thinking config updated",{config:e});}getThinking(){return this.thinkingSettings}convertMessages(e){let t=this.filterIncompleteToolCalls(e),s=[],n=[],r=[],i=()=>{r.length>0&&(n.push({parts:r,role:"user"}),r=[]);};for(let l of t)if(l.role==="system"){let c=me(l.content);c&&s.push(c);}else if(l.role==="user"){i();let c=[];if(typeof l.content=="string")c.push({text:l.content});else if(Array.isArray(l.content)){for(let u of l.content)if(u.type==="text")c.push({text:u.text});else if(u.type==="image_url"){let d=u.image_url.url;if(d.startsWith("data:")){let p=d.match(/^data:([^;]+);base64,(.+)$/);p&&c.push({inlineData:{mimeType:p[1],data:p[2]}});}}}n.push({parts:c,role:"user"});}else if(l.role==="assistant"){i();let c=[],u=me(l.content);if(u&&c.push({text:u}),l.tool_calls)for(let d of l.tool_calls){let p={functionCall:{name:d.function.name,args:gw(d.function.arguments),id:d.id}};d.thoughtSignature&&(p.thoughtSignature=d.thoughtSignature),c.push(p);}n.push({parts:c,role:"model"});}else if(l.role==="tool"){let c=me(l.content)||"",d={name:l.name||"unknown",response:{output:c}};l.tool_call_id&&(d.id=l.tool_call_id),r.push({functionResponse:d});}i();let o={contents:n};return s.length>0&&(o.systemInstruction={parts:s.map(l=>({text:l})),role:"user"}),o}filterIncompleteToolCalls(e){let t=[],s=0;for(;s<e.length;){let n=e[s];if(n.role==="system"){t.push(n),s++;continue}if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){let r=n.tool_calls,i=r.length,o=r.every(g=>!!g.id),l=[],c=[],u=s+1;for(;u<e.length;){let g=e[u];if(g.role==="system"){l.push(g),u++;continue}if(g.role!=="tool")break;l.push(g),c.push(g),u++;}let d=c.length,p=c.every(g=>!!g.tool_call_id),h=d===i;if(h&&o&&p){let g=new Set(c.map(f=>f.tool_call_id).filter(f=>!!f));for(let f of r)if(!g.has(f.id)){h=false;break}}if(h){t.push(n);for(let g of l)t.push(g);}else {process.env.CLI_DEBUG==="1"&&m.debug("GEMINI","Filtering incomplete tool call turn",{toolCalls:r.map(g=>({id:g.id,name:g.function.name})),responseCount:d});for(let g of l)g.role==="system"&&t.push(g);}s=u;continue}if(n.role==="tool"){process.env.CLI_DEBUG==="1"&&m.debug("GEMINI","Dropping orphan tool message",{toolCallId:n.tool_call_id,toolName:n.name}),s++;continue}t.push(n),s++;}return t}convertTools(e){return !e||e.length===0?[]:[{functionDeclarations:e.map(s=>({name:s.name,description:s.description,parameters:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties},parametersJsonSchema:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties}}))}]}buildGenerationConfig(e){let t={temperature:e.temperature??1,topP:e.topP??.95,topK:e.topK??64};return e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.stopSequences&&e.stopSequences.length>0&&(t.stopSequences=e.stopSequences),e.structuredOutput&&(t.responseMimeType="application/json",t.responseSchema=e.structuredOutput.schema),e.enableThinking&&(t.thinkingConfig={thinkingBudget:e.thinkingBudget??Hp,includeThoughts:true}),t}parseSSELine(e){let t=e.trim();if(!t||(t.startsWith("data:")&&(t=t.slice(5).trim()),t==="[DONE]")||!t.startsWith("{"))return null;try{return JSON.parse(t)}catch{return null}}convertResponse(e,t){let s=e.candidates[0];if(!s)throw new Error("No candidate in Gemini response");let n=s.content?.parts||[],r=null,i=[];for(let c of n)c.text?r=(r||"")+c.text:c.functionCall&&i.push({id:c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:c.functionCall.name,arguments:zp(c.functionCall.args)}});let o=e.usageMetadata||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0},l=s.finishReason==="STOP"?i.length>0?"tool_calls":"stop":(s.finishReason||"stop").toLowerCase();return {id:t,choices:[{message:{role:"assistant",content:r,tool_calls:i.length>0?i:void 0},finish_reason:l}],usage:{prompt_tokens:o.promptTokenCount,completion_tokens:o.candidatesTokenCount,total_tokens:o.totalTokenCount,cached_tokens:o.cachedContentTokenCount}}}async makeRequest(e,t){let s,n=0;for(;n<=this.retryConfig.requestMaxRetries;)try{return await e()}catch(r){s=r,n++;let i=ft(r),o=Jt(r.response?.headers?.["retry-after"]);if(!i.retryable||n>this.retryConfig.requestMaxRetries)break;let l=os(o,n,this.retryConfig);await gn(l);}throw s}async chat(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:r}=this.convertMessages(e),i=this.convertTools(t.tools||[]),o=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens}),l={contents:n,systemInstruction:r,generationConfig:o};i.length>0&&(l.tools=i);let c=`gemini-${Date.now()}`,u=`${this.pathPrefix}/${s}:generateContent`,d=this.authMode==="query"?{key:this.apiKey}:void 0;return this.makeRequest(async()=>{let p=await this.client.post(u,l,{params:d,signal:t.signal});return this.convertResponse(p.data,c)},"chat")}async*chatStreamed(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:r}=this.convertMessages(e),i=this.convertTools(t.tools||[]),o=Jp(s),l=this.thinkingSettings?.type==="enabled",c=this.thinkingSettings?.type==="disabled",u=t.enableThinking!==void 0?t.enableThinking:l?true:c?false:o,d=t.thinkingBudget??this.thinkingSettings?.budget??Hp,p=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens,enableThinking:u,thinkingBudget:d}),g={contents:Jp(s)?fw(n):n,systemInstruction:r,generationConfig:p};i.length>0&&(g.tools=i);let f=`gemini-${Date.now()}`,b=`${this.pathPrefix}/${s}:streamGenerateContent`,y=`${this.baseURL}${b}`,w=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"},C=new URL(y);for(let[M,F]of Object.entries(w))C.searchParams.append(M,F);let k={"Content-Type":"application/json",Accept:"*/*"};if(this.authMode==="header"?k["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(k.Authorization=`Bearer ${this.apiKey}`),process.env.CLI_DEBUG==="1"){m.info("GEMINI","=== Gemini Stream Request ==="),m.info("GEMINI",`URL: ${C.toString()}`),m.info("GEMINI",`Model: ${s}`),m.info("GEMINI",`AuthMode: ${this.authMode}`),m.info("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),m.info("GEMINI",`Contents: ${n.length} messages`);let M=Ft(C.toString(),k,g);m.info("GEMINI_CURL",M),m.debug("GEMINI","Request body:",{contentsCount:g.contents.length,hasSystemInstruction:!!g.systemInstruction,toolsCount:g.tools?.[0]?.functionDeclarations?.length||0,generationConfig:g.generationConfig});}if(process.env.CLI_DEBUG==="1"){ye("GEMINI","[Gemini Stream Request]"),ye("GEMINI",`URL: ${C.toString()}`),ye("GEMINI",`Model: ${s}`),ye("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),ye("GEMINI",`Contents: ${n.length} messages`);let M=Ft(C.toString(),k,g);ye("GEMINI_CURL",M);}let T=Date.now(),_=await this.makeRequest(async()=>{let M=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"};return await this.client.post(b,g,{params:M,responseType:"stream",signal:t.signal,headers:{Accept:"*/*","Accept-Language":"*","sec-fetch-mode":"cors","Accept-Encoding":"br, gzip, deflate"}})},"chatStreamed");process.env.CLI_DEBUG==="1"&&(ye("GEMINI","[Gemini Stream Started]"),ye("GEMINI",`Status: ${_.status}`)),yield*this.streamGenerator(_.data,f,T);}async*streamGenerator(e,t,s){let n="",r=[],i="",o=[],l,c=u=>{let d=[],p=u.candidates?.[0];if(!p)return process.env.CLI_DEBUG==="1"&&ye("GEMINI",`No candidate in response: ${JSON.stringify(u).slice(0,200)}`),d;u.usageMetadata&&(l=u.usageMetadata);let h=p.content?.parts;if(!h||h.length===0)process.env.CLI_DEBUG==="1"&&ye("GEMINI",`No parts in candidate: ${JSON.stringify(p).slice(0,200)}`);else for(let g of h){if(g.thought&&!g.thoughtSignature&&g.text){process.env.CLI_DEBUG==="1"&&ye("GEMINI",`Yielding reasoning: ${g.text.slice(0,50)}...`),d.push({choices:[{index:0,delta:{reasoning_content:g.text}}]});continue}if(g.text)g.thoughtSignature&&process.env.CLI_DEBUG==="1"?ye("GEMINI",`Yielding final answer (with signature): ${g.text.slice(0,100)}...`):process.env.CLI_DEBUG==="1"&&ye("GEMINI",`Yielding content: ${g.text.slice(0,100)}...`),i+=g.text,d.push({choices:[{index:0,delta:{content:g.text}}]});else if(g.functionCall){let f={id:g.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:g.functionCall.name,arguments:zp(g.functionCall.args)},...g.thoughtSignature?{thoughtSignature:g.thoughtSignature}:{}};o.push(f),d.push({choices:[{index:0,delta:{tool_calls:[{index:o.length-1,id:f.id,type:"function",function:{name:f.function.name,arguments:f.function.arguments},...f.thoughtSignature?{thoughtSignature:f.thoughtSignature}:{}}]}}]});}}if(p.finishReason){let g=l||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};if(process.env.CLI_DEBUG==="1"){let b=s?Date.now()-s:0;m.info("GEMINI","=== Gemini Stream Complete ==="),m.info("GEMINI",`Duration: ${b}ms`),m.info("GEMINI",`Finish Reason: ${p.finishReason}`),m.info("GEMINI",`Tool Calls: ${o.length}`),m.info("GEMINI",`Accumulated Content Length: ${i.length}`),m.info("GEMINI",`Usage: prompt=${g.promptTokenCount}, completion=${g.candidatesTokenCount}, total=${g.totalTokenCount}`),i&&m.info("GEMINI",`Content Preview: ${i.slice(0,500)}...`),o.length>0&&m.info("GEMINI","Tool Calls Detail:",o.map(y=>({id:y.id,name:y.function.name,argsLength:y.function.arguments.length})));}if(process.env.CLI_DEBUG==="1"){let b=s?Date.now()-s:0;ye("GEMINI","[Gemini Stream Complete]"),ye("GEMINI",`Duration: ${b}ms`),ye("GEMINI",`Finish Reason: ${p.finishReason}`),ye("GEMINI",`Tool Calls: ${o.length}`),ye("GEMINI",`Accumulated Content Length: ${i.length}`),ye("GEMINI",`Usage: prompt=${g.promptTokenCount}, completion=${g.candidatesTokenCount}, total=${g.totalTokenCount}`),i&&ye("GEMINI",`Content Preview: ${i.slice(0,500)}`);}let f=p.finishReason==="STOP"?o.length>0?"tool_calls":"stop":p.finishReason.toLowerCase();d.push({id:t,choices:[{index:0,delta:{},finish_reason:f}],usage:{prompt_tokens:g.promptTokenCount,completion_tokens:g.candidatesTokenCount,total_tokens:g.totalTokenCount,cached_tokens:g.cachedContentTokenCount}});}return d};try{for await(let u of e){let d=u.toString();n+=d,process.env.CLI_DEBUG==="1"&&ye("GEMINI",`Raw chunk (${d.length} bytes): ${d.slice(0,200)}...`);let p=n.split(/\r?\n/);n=p.pop()||"";for(let h of p){let g=h.trimEnd();if(!g){if(r.length===0)continue;let b=r.join(`
1749
+ 4. **Professional tone**: objective and technical`}getModelDisplayName(e){return e?e.includes("gemini-3")?"Gemini 3":e.includes("gemini-2.5")?"Gemini 2.5":e.includes("gemini-2.0")?"Gemini 2.0":e.includes("gemini-1.5")?"Gemini 1.5":e.includes("gemini-1.0")?"Gemini 1.0":e:"Gemini"}supportsVision(e){return e?e.includes("vision")?true:this.isModelType(e,"gemini-1.5*","gemini-2*","gemini-3*"):false}};W();function gw(a){let e="/v1beta/models";if(!a)return e;let t=a.trim();if(!t)return e;let s=t.startsWith("/")?t:`/${t}`;return s=s.replace(/\/+$/,""),s.includes("/models")||(s=`${s}/models`),s}function hw(a){try{let e=JSON.parse(a);return e&&typeof e=="object"?e:{value:e}}catch{return {}}}function zp(a){if(a==null)return "{}";if(typeof a=="string"){let e=a.trim();return e?e.startsWith("{")||e.startsWith("[")?e:JSON.stringify({value:e}):"{}"}try{return JSON.stringify(a)}catch{return "{}"}}var fw="skip_thought_signature_validator",Hp=8192;function Jp(a){return a.includes("gemini-3")||a.includes("preview")}function yw(a){let e=-1;for(let s=a.length-1;s>=0;s--){let n=a[s];if(n.role==="user"&&n.parts?.some(r=>r.text)){e=s;break}}if(e===-1)return a;let t=a.slice();for(let s=e;s<t.length;s++){let n=t[s];if(n.role==="model"&&n.parts){let r=n.parts.slice();for(let i=0;i<r.length;i++){let o=r[i];if(o.functionCall){o.thoughtSignature||(r[i]={...o,thoughtSignature:fw},t[s]={...n,parts:r});break}}}}return t}var vn=class{client;apiKey;baseURL;pathPrefix;userId;retryConfig;authMode;thinkingSettings=null;constructor(e,t="https://generativelanguage.googleapis.com",s,n){this.apiKey=e,this.baseURL=t.replace(/\/$/,""),this.pathPrefix=gw(n?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(n?.authMode),this.retryConfig=is(dn("gemini"),s);let r={"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${In__default.platform()}; ${In__default.arch()})`,"x-goog-api-client":"google-genai-sdk/1.30.0 gl-node/v22.16.0","x-gemini-api-privileged-user-id":this.userId};this.authMode==="header"?r["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(r.Authorization=`Bearer ${this.apiKey}`),this.client=ew.create({baseURL:this.baseURL,timeout:6e5,headers:r});}resolveAuthMode(e){if(e&&e!=="auto")return e;let t=this.baseURL.includes("generativelanguage.googleapis.com"),s=this.apiKey.startsWith("AIza");return t||s?"query":"bearer"}setThinking(e){this.thinkingSettings=e,process.env.CLI_DEBUG==="1"&&ye("GEMINI","Thinking config updated",{config:e});}getThinking(){return this.thinkingSettings}convertMessages(e){let t=this.filterIncompleteToolCalls(e),s=[],n=[],r=[],i=()=>{r.length>0&&(n.push({parts:r,role:"user"}),r=[]);};for(let l of t)if(l.role==="system"){let c=me(l.content);c&&s.push(c);}else if(l.role==="user"){i();let c=[];if(typeof l.content=="string")c.push({text:l.content});else if(Array.isArray(l.content)){for(let u of l.content)if(u.type==="text")c.push({text:u.text});else if(u.type==="image_url"){let d=u.image_url.url;if(d.startsWith("data:")){let p=d.match(/^data:([^;]+);base64,(.+)$/);p&&c.push({inlineData:{mimeType:p[1],data:p[2]}});}}}n.push({parts:c,role:"user"});}else if(l.role==="assistant"){i();let c=[],u=me(l.content);if(u&&c.push({text:u}),l.tool_calls)for(let d of l.tool_calls){let p={functionCall:{name:d.function.name,args:hw(d.function.arguments),id:d.id}};d.thoughtSignature&&(p.thoughtSignature=d.thoughtSignature),c.push(p);}n.push({parts:c,role:"model"});}else if(l.role==="tool"){let c=me(l.content)||"",d={name:l.name||"unknown",response:{output:c}};l.tool_call_id&&(d.id=l.tool_call_id),r.push({functionResponse:d});}i();let o={contents:n};return s.length>0&&(o.systemInstruction={parts:s.map(l=>({text:l})),role:"user"}),o}filterIncompleteToolCalls(e){let t=[],s=0;for(;s<e.length;){let n=e[s];if(n.role==="system"){t.push(n),s++;continue}if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){let r=n.tool_calls,i=r.length,o=r.every(g=>!!g.id),l=[],c=[],u=s+1;for(;u<e.length;){let g=e[u];if(g.role==="system"){l.push(g),u++;continue}if(g.role!=="tool")break;l.push(g),c.push(g),u++;}let d=c.length,p=c.every(g=>!!g.tool_call_id),h=d===i;if(h&&o&&p){let g=new Set(c.map(f=>f.tool_call_id).filter(f=>!!f));for(let f of r)if(!g.has(f.id)){h=false;break}}if(h){t.push(n);for(let g of l)t.push(g);}else {process.env.CLI_DEBUG==="1"&&m.debug("GEMINI","Filtering incomplete tool call turn",{toolCalls:r.map(g=>({id:g.id,name:g.function.name})),responseCount:d});for(let g of l)g.role==="system"&&t.push(g);}s=u;continue}if(n.role==="tool"){process.env.CLI_DEBUG==="1"&&m.debug("GEMINI","Dropping orphan tool message",{toolCallId:n.tool_call_id,toolName:n.name}),s++;continue}t.push(n),s++;}return t}convertTools(e){return !e||e.length===0?[]:[{functionDeclarations:e.map(s=>({name:s.name,description:s.description,parameters:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties},parametersJsonSchema:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties}}))}]}buildGenerationConfig(e){let t={temperature:e.temperature??1,topP:e.topP??.95,topK:e.topK??64};return e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.stopSequences&&e.stopSequences.length>0&&(t.stopSequences=e.stopSequences),e.structuredOutput&&(t.responseMimeType="application/json",t.responseSchema=e.structuredOutput.schema),e.enableThinking&&(t.thinkingConfig={thinkingBudget:e.thinkingBudget??Hp,includeThoughts:true}),t}parseSSELine(e){let t=e.trim();if(!t||(t.startsWith("data:")&&(t=t.slice(5).trim()),t==="[DONE]")||!t.startsWith("{"))return null;try{return JSON.parse(t)}catch{return null}}convertResponse(e,t){let s=e.candidates[0];if(!s)throw new Error("No candidate in Gemini response");let n=s.content?.parts||[],r=null,i=[];for(let c of n)c.text?r=(r||"")+c.text:c.functionCall&&i.push({id:c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:c.functionCall.name,arguments:zp(c.functionCall.args)}});let o=e.usageMetadata||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0},l=s.finishReason==="STOP"?i.length>0?"tool_calls":"stop":(s.finishReason||"stop").toLowerCase();return {id:t,choices:[{message:{role:"assistant",content:r,tool_calls:i.length>0?i:void 0},finish_reason:l}],usage:{prompt_tokens:o.promptTokenCount,completion_tokens:o.candidatesTokenCount,total_tokens:o.totalTokenCount,cached_tokens:o.cachedContentTokenCount}}}async makeRequest(e,t){let s,n=0;for(;n<=this.retryConfig.requestMaxRetries;)try{return await e()}catch(r){s=r,n++;let i=ft(r),o=Jt(r.response?.headers?.["retry-after"]);if(!i.retryable||n>this.retryConfig.requestMaxRetries)break;let l=os(o,n,this.retryConfig);await gn(l);}throw s}async chat(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:r}=this.convertMessages(e),i=this.convertTools(t.tools||[]),o=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens}),l={contents:n,systemInstruction:r,generationConfig:o};i.length>0&&(l.tools=i);let c=`gemini-${Date.now()}`,u=`${this.pathPrefix}/${s}:generateContent`,d=this.authMode==="query"?{key:this.apiKey}:void 0;return this.makeRequest(async()=>{let p=await this.client.post(u,l,{params:d,signal:t.signal});return this.convertResponse(p.data,c)},"chat")}async*chatStreamed(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:r}=this.convertMessages(e),i=this.convertTools(t.tools||[]),o=Jp(s),l=this.thinkingSettings?.type==="enabled",c=this.thinkingSettings?.type==="disabled",u=t.enableThinking!==void 0?t.enableThinking:l?true:c?false:o,d=t.thinkingBudget??this.thinkingSettings?.budget??Hp,p=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens,enableThinking:u,thinkingBudget:d}),g={contents:Jp(s)?yw(n):n,systemInstruction:r,generationConfig:p};i.length>0&&(g.tools=i);let f=`gemini-${Date.now()}`,b=`${this.pathPrefix}/${s}:streamGenerateContent`,y=`${this.baseURL}${b}`,w=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"},C=new URL(y);for(let[M,F]of Object.entries(w))C.searchParams.append(M,F);let k={"Content-Type":"application/json",Accept:"*/*"};if(this.authMode==="header"?k["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(k.Authorization=`Bearer ${this.apiKey}`),process.env.CLI_DEBUG==="1"){m.info("GEMINI","=== Gemini Stream Request ==="),m.info("GEMINI",`URL: ${C.toString()}`),m.info("GEMINI",`Model: ${s}`),m.info("GEMINI",`AuthMode: ${this.authMode}`),m.info("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),m.info("GEMINI",`Contents: ${n.length} messages`);let M=Ft(C.toString(),k,g);m.info("GEMINI_CURL",M),m.debug("GEMINI","Request body:",{contentsCount:g.contents.length,hasSystemInstruction:!!g.systemInstruction,toolsCount:g.tools?.[0]?.functionDeclarations?.length||0,generationConfig:g.generationConfig});}if(process.env.CLI_DEBUG==="1"){ye("GEMINI","[Gemini Stream Request]"),ye("GEMINI",`URL: ${C.toString()}`),ye("GEMINI",`Model: ${s}`),ye("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),ye("GEMINI",`Contents: ${n.length} messages`);let M=Ft(C.toString(),k,g);ye("GEMINI_CURL",M);}let T=Date.now(),_=await this.makeRequest(async()=>{let M=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"};return await this.client.post(b,g,{params:M,responseType:"stream",signal:t.signal,headers:{Accept:"*/*","Accept-Language":"*","sec-fetch-mode":"cors","Accept-Encoding":"br, gzip, deflate"}})},"chatStreamed");process.env.CLI_DEBUG==="1"&&(ye("GEMINI","[Gemini Stream Started]"),ye("GEMINI",`Status: ${_.status}`)),yield*this.streamGenerator(_.data,f,T);}async*streamGenerator(e,t,s){let n="",r=[],i="",o=[],l,c=u=>{let d=[],p=u.candidates?.[0];if(!p)return process.env.CLI_DEBUG==="1"&&ye("GEMINI",`No candidate in response: ${JSON.stringify(u).slice(0,200)}`),d;u.usageMetadata&&(l=u.usageMetadata);let h=p.content?.parts;if(!h||h.length===0)process.env.CLI_DEBUG==="1"&&ye("GEMINI",`No parts in candidate: ${JSON.stringify(p).slice(0,200)}`);else for(let g of h){if(g.thought&&!g.thoughtSignature&&g.text){process.env.CLI_DEBUG==="1"&&ye("GEMINI",`Yielding reasoning: ${g.text.slice(0,50)}...`),d.push({choices:[{index:0,delta:{reasoning_content:g.text}}]});continue}if(g.text)g.thoughtSignature&&process.env.CLI_DEBUG==="1"?ye("GEMINI",`Yielding final answer (with signature): ${g.text.slice(0,100)}...`):process.env.CLI_DEBUG==="1"&&ye("GEMINI",`Yielding content: ${g.text.slice(0,100)}...`),i+=g.text,d.push({choices:[{index:0,delta:{content:g.text}}]});else if(g.functionCall){let f={id:g.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:g.functionCall.name,arguments:zp(g.functionCall.args)},...g.thoughtSignature?{thoughtSignature:g.thoughtSignature}:{}};o.push(f),d.push({choices:[{index:0,delta:{tool_calls:[{index:o.length-1,id:f.id,type:"function",function:{name:f.function.name,arguments:f.function.arguments},...f.thoughtSignature?{thoughtSignature:f.thoughtSignature}:{}}]}}]});}}if(p.finishReason){let g=l||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};if(process.env.CLI_DEBUG==="1"){let b=s?Date.now()-s:0;m.info("GEMINI","=== Gemini Stream Complete ==="),m.info("GEMINI",`Duration: ${b}ms`),m.info("GEMINI",`Finish Reason: ${p.finishReason}`),m.info("GEMINI",`Tool Calls: ${o.length}`),m.info("GEMINI",`Accumulated Content Length: ${i.length}`),m.info("GEMINI",`Usage: prompt=${g.promptTokenCount}, completion=${g.candidatesTokenCount}, total=${g.totalTokenCount}`),i&&m.info("GEMINI",`Content Preview: ${i.slice(0,500)}...`),o.length>0&&m.info("GEMINI","Tool Calls Detail:",o.map(y=>({id:y.id,name:y.function.name,argsLength:y.function.arguments.length})));}if(process.env.CLI_DEBUG==="1"){let b=s?Date.now()-s:0;ye("GEMINI","[Gemini Stream Complete]"),ye("GEMINI",`Duration: ${b}ms`),ye("GEMINI",`Finish Reason: ${p.finishReason}`),ye("GEMINI",`Tool Calls: ${o.length}`),ye("GEMINI",`Accumulated Content Length: ${i.length}`),ye("GEMINI",`Usage: prompt=${g.promptTokenCount}, completion=${g.candidatesTokenCount}, total=${g.totalTokenCount}`),i&&ye("GEMINI",`Content Preview: ${i.slice(0,500)}`);}let f=p.finishReason==="STOP"?o.length>0?"tool_calls":"stop":p.finishReason.toLowerCase();d.push({id:t,choices:[{index:0,delta:{},finish_reason:f}],usage:{prompt_tokens:g.promptTokenCount,completion_tokens:g.candidatesTokenCount,total_tokens:g.totalTokenCount,cached_tokens:g.cachedContentTokenCount}});}return d};try{for await(let u of e){let d=u.toString();n+=d,process.env.CLI_DEBUG==="1"&&ye("GEMINI",`Raw chunk (${d.length} bytes): ${d.slice(0,200)}...`);let p=n.split(/\r?\n/);n=p.pop()||"";for(let h of p){let g=h.trimEnd();if(!g){if(r.length===0)continue;let b=r.join(`
1750
1750
  `);r=[];let y=this.parseSSELine(b);if(!y){process.env.CLI_DEBUG==="1"&&b.length>0&&ye("GEMINI",`Failed to parse event: ${b.slice(0,100)}...`);continue}for(let w of c(y))yield w;continue}if(g.startsWith("data:")){r.push(g.slice(5).trimStart());continue}let f=this.parseSSELine(g);if(!f){process.env.CLI_DEBUG==="1"&&g.length>0&&ye("GEMINI",`Failed to parse line: ${g.slice(0,100)}...`);continue}for(let b of c(f))yield b;}}if(r.length>0){let u=this.parseSSELine(r.join(`
1751
- `));if(u)for(let d of c(u))yield d;}}catch(u){if(process.env.CLI_DEBUG==="1"){let d=s?Date.now()-s:0;ye("GEMINI","[Gemini Stream Error]"),ye("GEMINI",`Duration: ${d}ms`),ye("GEMINI",`Error: ${u.message||u}`),u.response?.data&&ye("GEMINI",`Response: ${JSON.stringify(u.response.data)}`);}throw u}}};W();var oo=class extends Lt{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new io,this.promptBuilder=new xr,this.defaultModel=e.defaultModel||"gemini-2.5-flash";let{apiKey:t,baseUrl:s,urlSuffix:n,retry:r}=e;this.provider=new vn(t,s,r,{pathPrefix:n});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("GeminiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("GeminiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences,signal:t.signal});}getProvider(){return this.provider}};var Ot=class a{static createAdapter(e,t){switch(e){case "openai":return a.createOpenAIAdapter(t,false);case "openai-responses":return a.createOpenAIAdapter(t,true);case "kimi":return a.createKimiAdapter(t);case "anthropic":case "anthropic-openai":return a.createAnthropicAdapter(t);case "doubao":throw new Error("Doubao adapter not yet implemented. Use Phase 5.");case "gemini":return a.createGeminiAdapter(t);default:throw new Error(`Unsupported provider protocol: ${e}`)}}static createOpenAIAdapter(e,t){let s={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,useResponsesAPI:t,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new Qi(s)}static createAnthropicAdapter(e){let t={authToken:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens&&e.maxTokens<=8192?e.maxTokens:void 0,disableCaching:false};return new so(t)}static createKimiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new ro(t)}static createGeminiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,urlSuffix:e.urlSuffix,defaultModel:e.defaultModel||e.lastSelectedModel,retry:e.retry};return new oo(t)}static isProtocolSupported(e){return ["openai","openai-responses","anthropic","anthropic-openai","kimi","gemini"].includes(e)}static getProtocolDisplayName(e){return {openai:"OpenAI (Chat Completions)","openai-responses":"OpenAI (Responses API)",anthropic:"Anthropic (Claude)","anthropic-openai":"Anthropic (OpenAI Format)",doubao:"\u8C46\u5305 (Doubao)",gemini:"Google Gemini",kimi:"Kimi (Moonshot)"}[e]||e}};var bw=16e3;function vw(a,e=bw){if(!a||a.length<=e)return a;let t=a.split(`
1751
+ `));if(u)for(let d of c(u))yield d;}}catch(u){if(process.env.CLI_DEBUG==="1"){let d=s?Date.now()-s:0;ye("GEMINI","[Gemini Stream Error]"),ye("GEMINI",`Duration: ${d}ms`),ye("GEMINI",`Error: ${u.message||u}`),u.response?.data&&ye("GEMINI",`Response: ${JSON.stringify(u.response.data)}`);}throw u}}};W();var oo=class extends Lt{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new io,this.promptBuilder=new xr,this.defaultModel=e.defaultModel||"gemini-2.5-flash";let{apiKey:t,baseUrl:s,urlSuffix:n,retry:r}=e;this.provider=new vn(t,s,r,{pathPrefix:n});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("GeminiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&m.warn("GeminiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences,signal:t.signal});}getProvider(){return this.provider}};var Ot=class a{static createAdapter(e,t){switch(e){case "openai":return a.createOpenAIAdapter(t,false);case "openai-responses":return a.createOpenAIAdapter(t,true);case "kimi":return a.createKimiAdapter(t);case "anthropic":case "anthropic-openai":return a.createAnthropicAdapter(t);case "doubao":throw new Error("Doubao adapter not yet implemented. Use Phase 5.");case "gemini":return a.createGeminiAdapter(t);default:throw new Error(`Unsupported provider protocol: ${e}`)}}static createOpenAIAdapter(e,t){let s={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,useResponsesAPI:t,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new Qi(s)}static createAnthropicAdapter(e){let t={authToken:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens&&e.maxTokens<=8192?e.maxTokens:void 0,disableCaching:false};return new so(t)}static createKimiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new ro(t)}static createGeminiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,urlSuffix:e.urlSuffix,defaultModel:e.defaultModel||e.lastSelectedModel,retry:e.retry};return new oo(t)}static isProtocolSupported(e){return ["openai","openai-responses","anthropic","anthropic-openai","kimi","gemini"].includes(e)}static getProtocolDisplayName(e){return {openai:"OpenAI (Chat Completions)","openai-responses":"OpenAI (Responses API)",anthropic:"Anthropic (Claude)","anthropic-openai":"Anthropic (OpenAI Format)",doubao:"\u8C46\u5305 (Doubao)",gemini:"Google Gemini",kimi:"Kimi (Moonshot)"}[e]||e}};var vw=16e3;function ww(a,e=vw){if(!a||a.length<=e)return a;let t=a.split(`
1752
1752
  `).length,s=a.length,n=Math.floor(e*.4),r=Math.floor(e*.4),i=n,o=a.length-r;for(;i>0&&(a.charCodeAt(i)&192)===128;)i--;for(;o<a.length&&(a.charCodeAt(o)&192)===128;)o++;let l=a.slice(0,i),c=a.slice(o),d=`
1753
1753
 
1754
1754
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1755
1755
 
1756
- `;return l+d+c}var ao=class{client;defaultModel;retryConfig;baseUrl;thinking;reasoning;caching;store;lastResponseId=null;sessionResponseIds=new Map;constructor(e){this.baseUrl=e.baseUrl||"https://ark.cn-beijing.volces.com/api/v3",this.defaultModel=e.defaultModel||"doubao-seed-1-6-251015",this.thinking=e.thinking,this.reasoning=e.reasoning,this.caching=e.caching||{type:"enabled"},this.store=e.store??true,this.client=Zv.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:18e4}),this.retryConfig=is(void 0,{requestMaxRetries:3,streamMaxRetries:5,...e.retry}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao] Initialized with:",{baseUrl:this.baseUrl,defaultModel:this.defaultModel,thinking:this.thinking,caching:this.caching,store:this.store});}async chat(e,t={}){let s="",n="",r=[],i,o;for await(let l of this.chatStreamed(e,t)){let c=l.choices?.[0]?.delta;if(c&&(c.content&&(s+=c.content),c.reasoning_content&&(n+=c.reasoning_content),c.tool_calls))for(let u of c.tool_calls){let d=r.find(p=>p.index===u.index);d?u.function?.arguments&&(d.function.arguments+=u.function.arguments):r.push({id:u.id||`call_${r.length}`,type:"function",function:{name:u.function?.name||"",arguments:u.function?.arguments||""},index:u.index});}l.usage&&(i=l.usage),l.id&&(o=l.id);}return o&&(this.lastResponseId=o,t.sessionId&&this.sessionResponseIds.set(t.sessionId,o)),{id:o||`chatcmpl-${Date.now()}`,choices:[{message:{role:"assistant",content:s||null,reasoning_content:n||void 0,...r.length>0?{tool_calls:r}:{}},finish_reason:r.length>0?"tool_calls":"stop"}],usage:i||{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}async*chatStreamed(e,t={}){let{model:s=this.defaultModel,tools:n,temperature:r=.7,sessionId:i,signal:o}=t,l=t.previousResponseId;!l&&i&&(l=this.sessionResponseIds.get(i)),l||(l=this.lastResponseId||void 0);let c=this.buildPayload(e,{model:s,tools:n,temperature:r,structuredOutput:t.structuredOutput,maxInputTokens:t.maxInputTokens,previousResponseId:l}),u=`${this.baseUrl}/responses`;ge.llmRequest("doubao-responses",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1756
+ `;return l+d+c}var ao=class{client;defaultModel;retryConfig;baseUrl;thinking;reasoning;caching;store;lastResponseId=null;sessionResponseIds=new Map;constructor(e){this.baseUrl=e.baseUrl||"https://ark.cn-beijing.volces.com/api/v3",this.defaultModel=e.defaultModel||"doubao-seed-1-6-251015",this.thinking=e.thinking,this.reasoning=e.reasoning,this.caching=e.caching||{type:"enabled"},this.store=e.store??true,this.client=ew.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:18e4}),this.retryConfig=is(void 0,{requestMaxRetries:3,streamMaxRetries:5,...e.retry}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao] Initialized with:",{baseUrl:this.baseUrl,defaultModel:this.defaultModel,thinking:this.thinking,caching:this.caching,store:this.store});}async chat(e,t={}){let s="",n="",r=[],i,o;for await(let l of this.chatStreamed(e,t)){let c=l.choices?.[0]?.delta;if(c&&(c.content&&(s+=c.content),c.reasoning_content&&(n+=c.reasoning_content),c.tool_calls))for(let u of c.tool_calls){let d=r.find(p=>p.index===u.index);d?u.function?.arguments&&(d.function.arguments+=u.function.arguments):r.push({id:u.id||`call_${r.length}`,type:"function",function:{name:u.function?.name||"",arguments:u.function?.arguments||""},index:u.index});}l.usage&&(i=l.usage),l.id&&(o=l.id);}return o&&(this.lastResponseId=o,t.sessionId&&this.sessionResponseIds.set(t.sessionId,o)),{id:o||`chatcmpl-${Date.now()}`,choices:[{message:{role:"assistant",content:s||null,reasoning_content:n||void 0,...r.length>0?{tool_calls:r}:{}},finish_reason:r.length>0?"tool_calls":"stop"}],usage:i||{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}async*chatStreamed(e,t={}){let{model:s=this.defaultModel,tools:n,temperature:r=.7,sessionId:i,signal:o}=t,l=t.previousResponseId;!l&&i&&(l=this.sessionResponseIds.get(i)),l||(l=this.lastResponseId||void 0);let c=this.buildPayload(e,{model:s,tools:n,temperature:r,structuredOutput:t.structuredOutput,maxInputTokens:t.maxInputTokens,previousResponseId:l}),u=`${this.baseUrl}/responses`;ge.llmRequest("doubao-responses",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1757
1757
  [Doubao Responses API Request]`),console.log("URL:",u),console.log("Payload:",JSON.stringify(c,null,2)));let d=this.retryConfig.streamMaxRetries,p=0;for(;;)try{if(o?.aborted){let b=new Error("Request aborted");throw b.name="AbortError",b}let h=Date.now(),g=await this.client.post("/responses",c,{responseType:"stream",signal:o,headers:{Accept:"text/event-stream"}});if(process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1758
1758
  [Doubao Stream Started]`),console.log("Status:",g.status)),g.status!==200){let b="";for await(let y of g.data)b+=y.toString();throw new Error(`Doubao API error: ${g.status} - ${b}`)}yield*this.parseStreamResponse(g.data);let f=Date.now()-h;ge.llmResponse("doubao-responses",f,{},{}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1759
1759
  [Doubao Stream Complete]`),console.log("Duration:",`${f}ms`));return}catch(h){let g="";if(h.response?.data)try{if(typeof h.response.data.on=="function"){let b=[];for await(let w of h.response.data)b.push(Buffer.from(w));let y=Buffer.concat(b).toString("utf-8");try{let w=JSON.parse(y),C=w.error||{message:w.message,code:w.code,type:w.type};g=JSON.stringify(C,null,2);}catch{g=y;}}else if(typeof h.response.data=="string")g=h.response.data;else if(h.response.data.error){let b=h.response.data.error,y={message:b.message,code:b.code,type:b.type};g=JSON.stringify(y,null,2);}else {let b=h.response.data,y={message:b.message,code:b.code,type:b.type,error:b.error};g=JSON.stringify(y,null,2);}}catch(b){g=`HTTP ${h.response?.status||"unknown"} (\u65E0\u6CD5\u8BFB\u53D6\u54CD\u5E94\u4F53: ${b})`;}let f=ft(h);if(process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1760
1760
  [Doubao Stream Error]`),console.log("Message:",h.message),console.log("Status:",h.response?.status),console.log("Error Details:",g||"none"),console.log("Retryable:",f.retryable)),g&&(f.message=`${h.message}
1761
1761
  ${g}`),ge.llmError("doubao-responses",h),f.retryable&&p<d){p++;let b=h.response?.headers?.["retry-after"],y=Jt(b),w=os(y,p,this.retryConfig);console.log(`[Doubao] Stream failed (${f.code}), reconnecting in ${nt(w)} (${p}/${d})...`),yield {choices:[],type:"stream_retry",error:f.message,errorCode:f.code,attempt:p,maxRetries:d,delayMs:w};try{await As(w,t.signal);}catch(C){throw C?.name==="AbortError",C}continue}throw f}}getResponseId(e){return e?this.sessionResponseIds.get(e)||null:this.lastResponseId}setResponseId(e,t){this.lastResponseId=e,t&&this.sessionResponseIds.set(t,e);}clearSession(e){e?this.sessionResponseIds.delete(e):this.lastResponseId=null;}setThinking(e){this.thinking=e;}setCaching(e){this.caching=e;}buildPayload(e,t){let {model:s,tools:n,temperature:r,structuredOutput:i,maxInputTokens:o,previousResponseId:l}=t,c=this.convertToDoubaoInput(e,l);this.extractSystemInstructions(e);let d={model:s,input:c,stream:true,temperature:r};return l&&(d.previous_response_id=l),this.thinking&&(d.thinking=this.thinking),this.reasoning&&(d.reasoning=this.reasoning),n&&n.length>0&&(d.tools=n.map(p=>({type:"function",name:p.name,description:p.description,parameters:p.parameters})),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Doubao] Added ${d.tools.length} tools`)),i&&(d.text={format:{type:"json_schema",name:i.name,schema:i.schema}}),d}extractSystemInstructions(e){let t=e.filter(s=>s.role==="system").map(s=>me(s.content).trim()).filter(s=>s.length>0);return t.length>0?t.join(`
1762
1762
 
1763
- `):void 0}convertToDoubaoInput(e,t){let s=new Map;if(!e.some(i=>i.role==="tool"||i.role==="assistant"&&Array.isArray(i.tool_calls)&&i.tool_calls.length>0))return e.map(i=>({role:i.role,content:me(i.content)}));let r=e.filter(i=>i.role!=="system");if(t){let i=[],o=false;for(let l=r.length-1;l>=0;l--){let c=r[l];if(c.role==="user"&&!o)i.unshift(...this.convertMessageToInputItems(c,s)),o=true;else if(c.role==="tool"&&o)i.unshift(...this.convertMessageToInputItems(c,s));else if(o)break}return i}return r.flatMap(i=>this.convertMessageToInputItems(i,s)).filter(i=>i!==null)}convertMessageToInputItems(e,t){if(e.role==="assistant"){let n=[],r=me(e.content);if(r.trim().length>0&&n.push({type:"message",role:"assistant",status:"completed",content:[{type:"input_text",text:r}]}),Array.isArray(e.tool_calls)&&e.tool_calls.length>0)for(let i of e.tool_calls){let o=this.normalizeCallId(i.id,t);n.push({type:"function_call",id:o,call_id:o,name:i.function.name,arguments:i.function.arguments||"",status:"completed"});}return n}if(e.role==="tool"){let n=this.normalizeCallId(e.tool_call_id||e.name,t),r=me(e.content),i=vw(r);return [{type:"function_call_output",call_id:n,output:i}]}if(Array.isArray(e.content)){let n=[];for(let r of e.content)r.type==="text"&&r.text.trim()?n.push({type:"input_text",text:r.text}):r.type==="image_url"&&n.push({type:"input_image",image_url:r.image_url.url});return n.length===0?[]:[{type:"message",role:"user",content:n}]}let s=me(e.content);return !s||s.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:s}]}]}normalizeCallId(e,t){if(e&&t.has(e))return t.get(e);let s;return e?s=e.startsWith("fc_")?e:`fc_${e}`:s=`fc_${Math.random().toString(36).slice(2,10)}`,e?t.set(e,s):t.set(s,s),s}async*parseStreamResponse(e){let t="",s=new Map,n=0,r=null,i=null,o=false,l=false,c,u=p=>{let h={...p};return l||(h.role="assistant",l=true),{id:c,choices:[{index:0,delta:h}]}};for await(let p of e){t+=p.toString();let h=t.split(`
1763
+ `):void 0}convertToDoubaoInput(e,t){let s=new Map;if(!e.some(i=>i.role==="tool"||i.role==="assistant"&&Array.isArray(i.tool_calls)&&i.tool_calls.length>0))return e.map(i=>({role:i.role,content:me(i.content)}));let r=e.filter(i=>i.role!=="system");if(t){let i=[],o=false;for(let l=r.length-1;l>=0;l--){let c=r[l];if(c.role==="user"&&!o)i.unshift(...this.convertMessageToInputItems(c,s)),o=true;else if(c.role==="tool"&&o)i.unshift(...this.convertMessageToInputItems(c,s));else if(o)break}return i}return r.flatMap(i=>this.convertMessageToInputItems(i,s)).filter(i=>i!==null)}convertMessageToInputItems(e,t){if(e.role==="assistant"){let n=[],r=me(e.content);if(r.trim().length>0&&n.push({type:"message",role:"assistant",status:"completed",content:[{type:"input_text",text:r}]}),Array.isArray(e.tool_calls)&&e.tool_calls.length>0)for(let i of e.tool_calls){let o=this.normalizeCallId(i.id,t);n.push({type:"function_call",id:o,call_id:o,name:i.function.name,arguments:i.function.arguments||"",status:"completed"});}return n}if(e.role==="tool"){let n=this.normalizeCallId(e.tool_call_id||e.name,t),r=me(e.content),i=ww(r);return [{type:"function_call_output",call_id:n,output:i}]}if(Array.isArray(e.content)){let n=[];for(let r of e.content)r.type==="text"&&r.text.trim()?n.push({type:"input_text",text:r.text}):r.type==="image_url"&&n.push({type:"input_image",image_url:r.image_url.url});return n.length===0?[]:[{type:"message",role:"user",content:n}]}let s=me(e.content);return !s||s.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:s}]}]}normalizeCallId(e,t){if(e&&t.has(e))return t.get(e);let s;return e?s=e.startsWith("fc_")?e:`fc_${e}`:s=`fc_${Math.random().toString(36).slice(2,10)}`,e?t.set(e,s):t.set(s,s),s}async*parseStreamResponse(e){let t="",s=new Map,n=0,r=null,i=null,o=false,l=false,c,u=p=>{let h={...p};return l||(h.role="assistant",l=true),{id:c,choices:[{index:0,delta:h}]}};for await(let p of e){t+=p.toString();let h=t.split(`
1764
1764
  `);t=h.pop()||"";for(let g of h){let f=g.trim();if(!f||!f.startsWith("data: "))continue;let b=f.slice(6);if(b==="[DONE]"){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao Stream] Received [DONE]");continue}let y;try{y=JSON.parse(b);}catch{process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao Stream] Invalid JSON:",b);continue}switch(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao Stream Event]",y.type,JSON.stringify(y,null,2).slice(0,200)),y.type){case "response.created":case "response.in_progress":y.response?.id&&(c=y.response.id);break;case "response.output_text.delta":{let w=typeof y.delta=="string"?y.delta:"";if(!w)break;o=true,yield u({content:w});break}case "response.reasoning_summary_text.delta":{let w=typeof y.delta=="string"?y.delta:"";if(!w)break;o=true,yield u({reasoning_content:w});break}case "response.reasoning_summary_part.added":case "response.reasoning_summary_part.done":break;case "response.output_item.added":{if(y.item?.type==="function_call"){let w=y.item,C=w.id||`item_${y.output_index}`,k={id:w.call_id||w.id||`call_${Date.now()}_${n}`,name:w.name,index:n++,arguments:""};s.set(C,k),o=true,yield u({tool_calls:[{index:k.index,id:k.id,type:"function",function:{name:k.name}}]});}else if(y.item?.type==="reasoning"){let w=y.item;if(w.summary?.length>0){let C=w.summary.map(k=>k.text).join(`
1765
1765
  `);C&&(yield u({reasoning_content:C}));}}break}case "response.function_call_arguments.delta":{let w=y.item_id?s.get(y.item_id):void 0;if(!w)break;let C=typeof y.delta=="string"?y.delta:"";if(!C)break;w.arguments+=C,o=true,yield u({tool_calls:[{index:w.index,id:w.id,type:"function",function:{name:w.name,arguments:C}}]});break}case "response.completed":{r=y.response||null,i=y.response?.usage||null,y.response?.id&&(c=y.response.id,this.lastResponseId=c);break}case "response.error":case "response.failed":{let w=y.error?.message||y.error?.code||"Doubao stream failed";throw new Error(w)}}}}if(!o&&r){let p=Array.isArray(r.output)?r.output:[],h="",g="";for(let f of p)if(f?.type==="message"&&Array.isArray(f.content))for(let b of f.content)b?.type==="output_text"&&typeof b.text=="string"&&(h+=b.text);else if(f?.type==="reasoning"){let b=f;b.summary?.length>0&&(g=b.summary.map(y=>y.text).join(`
1766
- `));}(h||g)&&(yield {id:c,choices:[{index:0,delta:{role:"assistant",content:h||void 0,reasoning_content:g||void 0}}]});}let d={id:c,choices:[{index:0,delta:{},finish_reason:s.size>0?"tool_calls":"stop"}]};i&&(d.usage=this.normalizeUsage(i)),yield d;}normalizeUsage(e){let t={prompt_tokens:e.input_tokens||0,completion_tokens:e.output_tokens||0,total_tokens:e.total_tokens||0};return e.input_tokens_details?.cached_tokens!==void 0&&(t.cached_tokens=e.input_tokens_details.cached_tokens,t.prompt_tokens_details={cached_tokens:e.input_tokens_details.cached_tokens}),e.output_tokens_details?.reasoning_tokens!==void 0&&(t.completion_tokens_details={reasoning_tokens:e.output_tokens_details.reasoning_tokens}),t}};var Ml="# \u4F1A\u8BDD\u5386\u53F2\u6458\u8981",ww=60,Cw=200,kw=`You are a highly skilled assistant tasked with summarizing conversation history.
1766
+ `));}(h||g)&&(yield {id:c,choices:[{index:0,delta:{role:"assistant",content:h||void 0,reasoning_content:g||void 0}}]});}let d={id:c,choices:[{index:0,delta:{},finish_reason:s.size>0?"tool_calls":"stop"}]};i&&(d.usage=this.normalizeUsage(i)),yield d;}normalizeUsage(e){let t={prompt_tokens:e.input_tokens||0,completion_tokens:e.output_tokens||0,total_tokens:e.total_tokens||0};return e.input_tokens_details?.cached_tokens!==void 0&&(t.cached_tokens=e.input_tokens_details.cached_tokens,t.prompt_tokens_details={cached_tokens:e.input_tokens_details.cached_tokens}),e.output_tokens_details?.reasoning_tokens!==void 0&&(t.completion_tokens_details={reasoning_tokens:e.output_tokens_details.reasoning_tokens}),t}};var Ml="# \u4F1A\u8BDD\u5386\u53F2\u6458\u8981",Cw=60,kw=200,Sw=`You are a highly skilled assistant tasked with summarizing conversation history.
1767
1767
 
1768
1768
  Your goal is to create a concise yet comprehensive summary that captures:
1769
1769
  1. The main topics and objectives discussed
@@ -1780,7 +1780,7 @@ Guidelines:
1780
1780
  - Write in the same language as the conversation (Chinese if Chinese, English if English)
1781
1781
  - Format the summary clearly with sections if needed
1782
1782
 
1783
- Output only the summary, no additional commentary.`,Sw=`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u5BF9\u8BDD\u5386\u53F2\u603B\u7ED3\u52A9\u624B\u3002
1783
+ Output only the summary, no additional commentary.`,xw=`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u5BF9\u8BDD\u5386\u53F2\u603B\u7ED3\u52A9\u624B\u3002
1784
1784
 
1785
1785
  \u4F60\u7684\u76EE\u6807\u662F\u521B\u5EFA\u4E00\u4E2A\u7B80\u6D01\u4F46\u5168\u9762\u7684\u6458\u8981\uFF0C\u9700\u8981\u5305\u542B\uFF1A
1786
1786
  1. \u8BA8\u8BBA\u7684\u4E3B\u8981\u4E3B\u9898\u548C\u76EE\u6807
@@ -1797,7 +1797,7 @@ Output only the summary, no additional commentary.`,Sw=`\u4F60\u662F\u4E00\u4E2A
1797
1797
  - \u4F7F\u7528\u4E0E\u5BF9\u8BDD\u76F8\u540C\u7684\u8BED\u8A00\uFF08\u4E2D\u6587\u5BF9\u8BDD\u7528\u4E2D\u6587\uFF0C\u82F1\u6587\u5BF9\u8BDD\u7528\u82F1\u6587\uFF09
1798
1798
  - \u5982\u679C\u9700\u8981\uFF0C\u4F7F\u7528\u5206\u8282\u6765\u6E05\u6670\u5730\u683C\u5F0F\u5316\u6458\u8981
1799
1799
 
1800
- \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4E0D\u8981\u6DFB\u52A0\u989D\u5916\u7684\u8BC4\u8BBA\u3002`;function xw(a){for(let e of a){let t=me(e.content);if(/[\u4e00-\u9fa5]/.test(t))return "zh"}return "en"}function Tw(a){let e=[];for(let t of a){let s=t.role==="assistant"?"Assistant":t.role==="user"?"User":t.role==="tool"?"Tool Result":t.role,n=me(t.content),r="";if(t.tool_calls?.length&&(r=` [Called tools: ${t.tool_calls.map(o=>o.function.name).join(", ")}]`),n||r){let i=n.length>1e3?n.slice(0,1e3)+"...[truncated]":n;e.push(`[${s}]${r}
1800
+ \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4E0D\u8981\u6DFB\u52A0\u989D\u5916\u7684\u8BC4\u8BBA\u3002`;function Tw(a){for(let e of a){let t=me(e.content);if(/[\u4e00-\u9fa5]/.test(t))return "zh"}return "en"}function _w(a){let e=[];for(let t of a){let s=t.role==="assistant"?"Assistant":t.role==="user"?"User":t.role==="tool"?"Tool Result":t.role,n=me(t.content),r="";if(t.tool_calls?.length&&(r=` [Called tools: ${t.tool_calls.map(o=>o.function.name).join(", ")}]`),n||r){let i=n.length>1e3?n.slice(0,1e3)+"...[truncated]":n;e.push(`[${s}]${r}
1801
1801
  ${i}`);}}return `Please summarize the following conversation history:
1802
1802
 
1803
1803
  ---
@@ -1807,12 +1807,12 @@ ${e.join(`
1807
1807
  `)}
1808
1808
  ---
1809
1809
 
1810
- Provide a comprehensive summary:`}function Tr(a){let t=me(a.content).length,s=a.tool_calls?JSON.stringify(a.tool_calls).length:0;return Math.ceil((t+s)/4)}function Dl(a,e){return a.length<=e?a:a.slice(0,e-1).trimEnd()+"\u2026"}function _w(a){return a.replace(/\s+/g," ").trim()}function Pl(a,e){if(a.length===0)return {summary:"",lines:0};let t=[];for(let n of a){if(t.length>=ww)break;let r=n.role==="assistant"?"Assistant":n.role==="user"?"User":n.role,i=me(n.content),l=(i?_w(i):"")||(n.tool_calls?.length?`Tool calls: ${n.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${r}] ${Dl(l,Cw)}`);}return {summary:`${e}
1810
+ Provide a comprehensive summary:`}function Tr(a){let t=me(a.content).length,s=a.tool_calls?JSON.stringify(a.tool_calls).length:0;return Math.ceil((t+s)/4)}function Dl(a,e){return a.length<=e?a:a.slice(0,e-1).trimEnd()+"\u2026"}function Rw(a){return a.replace(/\s+/g," ").trim()}function Pl(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}] ${Dl(l,kw)}`);}return {summary:`${e}
1811
1811
  ${t.join(`
1812
- `)}`,lines:t.length}}async function Ll(a){let{session:e,profile:t,llmProvider:s,model:n,onProgress:r,timeout:i=6e4,signal:o}=a,l=a.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;r?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((D,G)=>({entry:D,index:G})).filter(({entry:D})=>D.item.type==="message");if(u.length===0)return null;u.filter(({entry:D})=>D.item.data.role==="system");let p=u.filter(({entry:D})=>D.item.data.role!=="system");if(p.length===0)return null;let h=0,g=p.length;for(let D=p.length-1;D>=0;D--){let G=p[D].entry.item.data;if(h+=Tr(G),h>=l){g=D;break}}if(g>=p.length){if(p.length<=2)return null;g=Math.floor(p.length/2);}let f=p.slice(0,g).map(({entry:D})=>D.item.data);if(f.length===0)return null;let b={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let D of f){let G=Tr(D);D.role==="user"?b.userTokens+=G:D.role==="assistant"?b.assistantTokens+=G:D.role==="tool"&&(b.toolTokens+=G),b.totalTokens+=G;}let y=p.slice(g).map(({entry:D})=>D.item.data),w={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let D of y){let G=Tr(D);D.role==="user"?w.userTokens+=G:D.role==="assistant"?w.assistantTokens+=G:D.role==="tool"&&(w.toolTokens+=G),w.totalTokens+=G;}let C=b.totalTokens;r?.("summarizing",`Summarizing ${f.length} messages with AI...`);let k=xw(f),T=k==="zh"?Sw:kw,_=Tw(f),M,F;try{let D=new AbortController,G=setTimeout(()=>D.abort(),i),q=o?AbortSignal.any([o,D.signal]):D.signal;try{let oe=await s.chat([{role:"system",content:T},{role:"user",content:_}],{model:n,temperature:.3,signal:q});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}=Pl(f,Ml);M=oe;}}catch(D){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",D.message);let{summary:G}=Pl(f,Ml);M=G;}r?.("saving","Saving compacted history...");let R=`${k==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
1812
+ `)}`,lines:t.length}}async function Ll(a){let{session:e,profile:t,llmProvider:s,model:n,onProgress:r,timeout:i=6e4,signal:o}=a,l=a.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;r?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((D,G)=>({entry:D,index:G})).filter(({entry:D})=>D.item.type==="message");if(u.length===0)return null;u.filter(({entry:D})=>D.item.data.role==="system");let p=u.filter(({entry:D})=>D.item.data.role!=="system");if(p.length===0)return null;let h=0,g=p.length;for(let D=p.length-1;D>=0;D--){let G=p[D].entry.item.data;if(h+=Tr(G),h>=l){g=D;break}}if(g>=p.length){if(p.length<=2)return null;g=Math.floor(p.length/2);}let f=p.slice(0,g).map(({entry:D})=>D.item.data);if(f.length===0)return null;let b={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let D of f){let G=Tr(D);D.role==="user"?b.userTokens+=G:D.role==="assistant"?b.assistantTokens+=G:D.role==="tool"&&(b.toolTokens+=G),b.totalTokens+=G;}let y=p.slice(g).map(({entry:D})=>D.item.data),w={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let D of y){let G=Tr(D);D.role==="user"?w.userTokens+=G:D.role==="assistant"?w.assistantTokens+=G:D.role==="tool"&&(w.toolTokens+=G),w.totalTokens+=G;}let C=b.totalTokens;r?.("summarizing",`Summarizing ${f.length} messages with AI...`);let k=Tw(f),T=k==="zh"?xw:Sw,_=_w(f),M,F;try{let D=new AbortController,G=setTimeout(()=>D.abort(),i),q=o?AbortSignal.any([o,D.signal]):D.signal;try{let oe=await s.chat([{role:"system",content:T},{role:"user",content:_}],{model:n,temperature:.3,signal:q});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}=Pl(f,Ml);M=oe;}}catch(D){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",D.message);let{summary:G}=Pl(f,Ml);M=G;}r?.("saving","Saving compacted history...");let R=`${k==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
1813
1813
 
1814
1814
  ${M}`,j=u.length-f.length,v=u[0]?.entry.timestamp??Date.now(),E={item:{type:"message",data:{role:"user",content:R,name:"SmartCompactSummary"}},timestamp:v,seq:0},L={item:{type:"compacted",data:{summary:Dl(M,2e3),originalCount:f.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:F}},timestamp:v,seq:0},I=[],A=false,O=new Set(p.slice(0,g).map(({entry:D})=>D));for(let D of c){if(D.item.type!=="message"){I.push({...D});continue}if(D.item.data.role==="system"){I.push({...D});continue}O.has(D)?A||(I.push({...E}),I.push({...L}),A=true):I.push({...D});}if(!A)return null;let $=I.map((D,G)=>({item:D.item,timestamp:D.timestamp??Date.now(),seq:G}));await e.replaceTimeline($);let P=Tr({content:R}),N={before:b,after:{userTokens:w.userTokens,assistantTokens:w.assistantTokens,toolTokens:w.toolTokens,summaryTokens:P,totalTokens:w.totalTokens+P},saved:{userTokens:b.userTokens,assistantTokens:b.assistantTokens,toolTokens:b.toolTokens,totalTokens:b.totalTokens-P}};return {removedMessages:f.length,keptMessages:j,summaryText:R,estimatedTokensSaved:C,llmTokensUsed:F,detailedStats:N}}async function Kp(a){let{session:e,profile:t}=a,s=a.tailTokenBudget??t.tailTokenBudget??2e4;if(!s||s<=0)return null;let n=await e.getTimeline(),r=n.map((T,_)=>({entry:T,index:_})).filter(({entry:T})=>T.item.type==="message");if(r.length===0)return null;r.filter(({entry:T})=>T.item.data.role==="system");let o=r.filter(({entry:T})=>T.item.data.role!=="system");if(o.length===0)return null;let l=0,c=o.length;for(let T=o.length-1;T>=0;T--){let _=o[T].entry.item.data;if(l+=Tr(_),l>=s){c=T;break}}if(c>=o.length){if(o.length<=2)return null;c=Math.floor(o.length/2);}let u=o.slice(0,c).map(({entry:T})=>T.item.data);if(u.length===0)return null;let{summary:d,lines:p}=Pl(u,a.summaryHeader??Ml);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:Dl(d,2e3),originalCount:u.length,compactedAt:new Date().toISOString()}},timestamp:g,seq:0},y=[],w=false,C=new Set(o.slice(0,c).map(({entry:T})=>T));for(let T of n){if(T.item.type!=="message"){y.push({...T});continue}if(T.item.data.role==="system"){y.push({...T});continue}C.has(T)?w||(y.push({...f}),y.push({...b}),w=true):y.push({...T});}if(!w)return null;let k=y.map((T,_)=>({item:T.item,timestamp:T.timestamp??Date.now(),seq:_}));return await e.replaceTimeline(k),{removedMessages:u.length,keptMessages:h,summaryText:d,summaryLines:p}}function Vp(a){if(!a.startsWith("mcp__"))return null;let e=a.split("__");if(e.length<3)return null;let t=e[1],s=e.slice(2).join("__");return !t||!s?null:{serverId:t,toolName:s}}var lo=class{extractFromAssistantMessage(e,t){if(!e||e.length===0)return;let s=[/I(?:'ll| will) (\w+.*?) to (.*?)(?:\.|$)/i,/Let me (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) going to (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) (\w+ing.*?) to (.*?)(?:\.|$)/i,/To (.*?)[,,] I(?:'ll| will) (\w+.*?)(?:\.|$)/i,/(?:First|Now|Next|Then)[,,] (?:I'll |I will |let me )?(\w+.*?)(?:\.|$)/i,/(?:我将|我会|让我)([^。,,]+)(?:来|以便|用于)([^。,,]+)/,/(?:首先|现在|接下来|然后)[,,](?:我将|我会|让我)?([^。,,]+)/];for(let i of s){let o=e.match(i);if(o){let l=o[2]||o[1];if(l&&l.length>0&&l.length<200)return l.trim()}}let n=t.toLowerCase(),r=e.split(/[.。!!??]/);for(let i of r)if(i.toLowerCase().includes(n)||i.toLowerCase().includes("read")||i.toLowerCase().includes("search")||i.toLowerCase().includes("file")){let o=i.trim();if(o.length>10&&o.length<200)return o}}extractActionFromToolName(e){return {readfile:"read",write_file:"write",create_file:"create",edit_file:"edit",Edit:"edit",search:"search",list_directory:"list",LS:"list",Glob:"find",find_files:"find",Execute:"execute",execute:"execute"}[e]||e.toLowerCase()}},co=class{generateEquivalentCommand(e,t){switch(e){case "search":return this.generateSearchCommand(t);case "Glob":case "find_files":return this.generateFindCommand(t);case "Execute":case "execute":return this.generateExecuteCommand(t);case "readfile":return this.generateReadCommand(t);case "list_directory":case "LS":return this.generateLsCommand(t);case "write_file":case "create_file":return this.generateWriteCommand(t);default:return}}generateSearchCommand(e){let t="rg";e.case_insensitive&&(t+=" -i"),e.line_numbers&&(t+=" -n"),e.context_lines?t+=` -C ${e.context_lines}`:e.context?t+=` -C ${e.context}`:(e.context_before&&(t+=` -B ${e.context_before}`),e.context_after&&(t+=` -A ${e.context_after}`));let s=e.pattern||"";t+=` "${this.escapeShellArg(s)}"`;let n=e.path||e.directory||".";return t+=` ${this.escapeShellPath(n)}`,e.type&&(t+=` --type=${e.type}`),e.file_pattern?t+=` -g "${this.escapeShellArg(e.file_pattern)}"`:e.glob_pattern&&(t+=` -g "${this.escapeShellArg(e.glob_pattern)}"`),t}generateFindCommand(e){let t="find",s=e.folder||e.path||".";if(t+=` ${this.escapeShellPath(s)}`,e.patterns&&Array.isArray(e.patterns)&&e.patterns.length>0)if(e.patterns.length===1)t+=` -name "${this.escapeShellArg(e.patterns[0])}"`;else {let n=e.patterns.map(r=>`-name "${this.escapeShellArg(r)}"`).join(" -o ");t+=` \\( ${n} \\)`;}return e.excludePatterns&&Array.isArray(e.excludePatterns)&&e.excludePatterns.forEach(n=>{t+=` ! -path "${this.escapeShellArg(n)}"`;}),e.maxDepth&&(t+=` -maxdepth ${e.maxDepth}`),e.type==="f"?t+=" -type f":e.type==="d"&&(t+=" -type d"),t}generateExecuteCommand(e){return e.command||""}generateReadCommand(e){let t=e.path||e.file_path||e.filename||"";if(e.start_line&&e.num_lines){let s=e.start_line+e.num_lines-1;return `sed -n '${e.start_line},${s}p' ${this.escapeShellPath(t)}`}return e.num_lines&&!e.start_line?`head -n ${e.num_lines} ${this.escapeShellPath(t)}`:`cat ${this.escapeShellPath(t)}`}generateLsCommand(e){let t="ls";(e.all||e.show_hidden)&&(t+=" -a"),(e.long||e.detailed)&&(t+=" -l"),t.includes("-")||(t+=" -la");let s=e.path||e.directory||e.directory_path||".";return t+=` ${this.escapeShellPath(s)}`,t}generateWriteCommand(e){let t=e.path||e.file_path||e.filename||"",s=e.content||"";return s.length<100&&!s.includes(`
1815
- `)?`echo "${this.escapeShellArg(s)}" > ${this.escapeShellPath(t)}`:`# Use editor to create ${t}`}escapeShellArg(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}escapeShellPath(e){return /[\s()[\]{}$`!*?<>|&;]/.test(e)?`"${this.escapeShellArg(e)}"`:e}};function Ds(a,e){let t=["path","file_path","filePath","filename","directory","folder","dir","file","output_path","input_path"];for(let s of t)if(e[s]&&typeof e[s]=="string")return e[s];switch(a){case "Execute":case "execute":if(e.command&&typeof e.command=="string"){let n=e.command,r=n.match(/(?:^|\s)([./~][\w/.-]+\.\w+)(?:\s|$)/);return r?r[1]:n.substring(0,50)+(n.length>50?"...":"")}break;case "search":return e.path||e.directory||".";case "Glob":case "find_files":let s=e.folder||e.path||".";return e.patterns&&Array.isArray(e.patterns)?`${s} (${e.patterns.join(", ")})`:s;case "read_multiple_files":if(e.files&&Array.isArray(e.files))return e.files.length>1?`${e.files.length} files`:e.files[0];break}}function Yp(a,e){let t=Vp(a);if(t)return `MCP ${t.serverId}/${t.toolName}`;switch(a){case "readfile":let s=Ds(a,e);return s?`Reading ${s}`:"Reading file";case "write_file":case "create_file":let n=Ds(a,e);return n?`Writing ${n}`:"Writing file";case "edit_file":case "Edit":let r=Ds(a,e);return r?`Editing ${r}`:"Editing file";case "search":let i=e.pattern||e.query;return i?`Searching for "${i}"`:"Searching code";case "list_directory":case "LS":return `Listing ${Ds(a,e)||"."}`;case "Glob":case "find_files":return e.patterns&&Array.isArray(e.patterns)?`Finding files: ${e.patterns.join(", ")}`:"Finding files";case "Execute":case "execute":let l=e.command||"";return l.length>60?`Running: ${l.substring(0,60)}...`:`Running: ${l}`;case "read_multiple_files":return e.files&&Array.isArray(e.files)?`Reading ${e.files.length} files`:"Reading multiple files";default:return `Executing ${a}`}}var uo=class{batchTimeWindow;activeBatches=new Map;pendingCalls=new Map;batchableTools=new Set(["readfile","write_file","create_file","list_directory","LS","Glob","find_files","read_multiple_files"]);constructor(e=200){this.batchTimeWindow=e;}detectBatch(e,t,s,n,r){if(!this.isBatchable(t))return {type:"single",merge:false};let i=this.pendingCalls.get(t)||[];if(i.length===0)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false};let o=i[i.length-1];if(r-o.startTime>this.batchTimeWindow)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false};if(i.some(u=>u.targetPath===s))return {type:"single",merge:false};if(i.length===1){let u=this.createBatch(o,e,s,r);return i.push({toolId:e,toolName:t,targetPath:s,startTime:r,args:n}),{type:"batch",merge:false,batchId:u,shouldCreateBatch:true}}else {let u=this.findActiveBatch(t);return u?(i.push({toolId:e,toolName:t,targetPath:s,startTime:r,args:n}),this.updateBatch(u,s,r),{type:"batch",merge:true,batchId:u}):(this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false})}}recordCompletion(e,t){let s=this.findActiveBatch(e);if(s){let n=this.activeBatches.get(s);n&&(n.completed++,n.completed>=n.total&&this.completeBatch(s));}}getBatchInfo(e){return this.activeBatches.get(e)}isBatchable(e){return this.batchableTools.has(e)}createBatch(e,t,s,n){let r=`batch-${e.toolName}-${n}`;return this.activeBatches.set(r,{batchId:r,toolName:e.toolName,targets:[e.targetPath,s],startTime:e.startTime,lastCallTime:n,completed:0,total:2}),r}updateBatch(e,t,s){let n=this.activeBatches.get(e);n&&(n.targets.push(t),n.total++,n.lastCallTime=s);}findActiveBatch(e){for(let[t,s]of this.activeBatches.entries())if(s.toolName===e)return t}completeBatch(e){this.activeBatches.delete(e);let t=this.activeBatches.get(e);t&&this.pendingCalls.delete(t.toolName);}cleanupExpiredBatches(e){let t=this.batchTimeWindow*5,s=[];this.activeBatches.forEach((r,i)=>{e-r.lastCallTime>t&&s.push(i);}),s.forEach(r=>this.completeBatch(r));let n=[];this.pendingCalls.forEach((r,i)=>{if(r.length>0){let o=r[r.length-1];e-o.startTime>t&&n.push(i);}}),n.forEach(r=>this.pendingCalls.delete(r));}reset(){this.activeBatches.clear(),this.pendingCalls.clear();}getStats(){let e=[];return this.activeBatches.forEach((t,s)=>{e.push({batchId:s,toolName:t.toolName,total:t.total,completed:t.completed});}),{activeBatches:this.activeBatches.size,pendingCalls:this.pendingCalls.size,batches:e}}};W();var Rw={default:["Thinking...","Processing...","Analyzing...","Pondering...","Contemplating..."]};var po={};function Aw(a,e,t=true){po[e]||(po[e]=0);let s=po[e]%a.length,n=a[s];return t&&(po[e]=(s+1)%a.length),n}function Xp(){let a=Rw.default;return Aw(a,"default")}function Qp(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 Zp(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 em(a,e,t){let s=pp(a,e,t),n=Gi(s);return {success:false,error:s.code,code:s.code,category:s.category,message:s.message,suggestion:n,retryable:s.retryable,receivedArgs:e?.substring(0,500)}}var mo=class{state="idle";lastStatusKey="";lastStatusAt=0;shouldEmit(e){if(e.type==="status"){let t=e.timestamp??Date.now(),s=`${e.status}:${e.message}`;if(s===this.lastStatusKey&&t-this.lastStatusAt<200)return false;this.lastStatusKey=s,this.lastStatusAt=t;}return this.transition(e),true}getState(){return this.state}transition(e){switch(e.type){case "thinking":case "reasoning":case "reasoning_complete":case "text":this.state="thinking";return;case "tool_call_start":this.state="tool_running";return;case "tool_call_end":case "tool_output":this.state="thinking";return;case "status":e.status==="tool_call"?this.state="tool_running":e.status==="thinking"?this.state="thinking":e.status==="complete"?this.state="completed":e.status==="error"&&(this.state="error");return;case "run_result":this.state="completed";return;case "error":case "error_classified":this.state="error";return;default:return}}};var sm=12e3,go=class{runner;memory;sessionManager;sessionSync;session;sessionEnabled;memoryPressure;compatProfile;workDir;model;systemPrompt;sandboxSetter;llmProvider;sessionSeed;sessionTotalInputTokens=0;sessionTotalOutputTokens=0;lastMemoryPressureState="unknown";autoCompactionInProgress=false;isRunning=false;shouldInterrupt=false;abortController=null;interruptResolver=null;interruptPromise=null;compressionMode="sync";eventEmitter=new EventEmitter;eventSequence=0;hostStateMachine=new mo;descriptionExtractor=new lo;commandGenerator=new co;lastAssistantMessage="";batchDetector=new uo;toolCallIdCounter=0;recentToolCalls=new Map;currentTaskMetadata;pendingInjectedMessages=[];constructor(e){this.runner=e.runner,this.memory=e.memory,this.sessionManager=e.sessionManager,this.sessionSync=e.sessionSync,this.session=e.session,this.sessionEnabled=e.sessionEnabled??true,this.workDir=te__default.resolve(e.workDir),this.model=e.model,this.systemPrompt=e.systemPrompt,this.memoryPressure=e.memoryPressure,this.compatProfile=e.compatProfile,this.sandboxSetter=e.setSandboxMode,this.llmProvider=e.llmProvider,this.sessionSeed=randomBytes(16).toString("hex"),this.syncWorkspaceEnv(),this.applyAnthropicSessionUserId();}on(e){return this.eventEmitter.on("event",e),()=>this.eventEmitter.off("event",e)}setWorkDir(e){this.workDir=te__default.resolve(e),this.syncWorkspaceEnv();}setSession(e,t){this.session=e||void 0,this.sessionSync=t,this.applyAnthropicSessionUserId();}applyAnthropicSessionUserId(){let t=this.llmProvider?.getProvider?.();if(!t||typeof t.setUserId!="function")return;let s=this.session?.sessionId,n=Pu(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(`
1815
+ `)?`echo "${this.escapeShellArg(s)}" > ${this.escapeShellPath(t)}`:`# Use editor to create ${t}`}escapeShellArg(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}escapeShellPath(e){return /[\s()[\]{}$`!*?<>|&;]/.test(e)?`"${this.escapeShellArg(e)}"`:e}};function Ds(a,e){let t=["path","file_path","filePath","filename","directory","folder","dir","file","output_path","input_path"];for(let s of t)if(e[s]&&typeof e[s]=="string")return e[s];switch(a){case "Execute":case "execute":if(e.command&&typeof e.command=="string"){let n=e.command,r=n.match(/(?:^|\s)([./~][\w/.-]+\.\w+)(?:\s|$)/);return r?r[1]:n.substring(0,50)+(n.length>50?"...":"")}break;case "search":return e.path||e.directory||".";case "Glob":case "find_files":let s=e.folder||e.path||".";return e.patterns&&Array.isArray(e.patterns)?`${s} (${e.patterns.join(", ")})`:s;case "read_multiple_files":if(e.files&&Array.isArray(e.files))return e.files.length>1?`${e.files.length} files`:e.files[0];break}}function Yp(a,e){let t=Vp(a);if(t)return `MCP ${t.serverId}/${t.toolName}`;switch(a){case "readfile":let s=Ds(a,e);return s?`Reading ${s}`:"Reading file";case "write_file":case "create_file":let n=Ds(a,e);return n?`Writing ${n}`:"Writing file";case "edit_file":case "Edit":let r=Ds(a,e);return r?`Editing ${r}`:"Editing file";case "search":let i=e.pattern||e.query;return i?`Searching for "${i}"`:"Searching code";case "list_directory":case "LS":return `Listing ${Ds(a,e)||"."}`;case "Glob":case "find_files":return e.patterns&&Array.isArray(e.patterns)?`Finding files: ${e.patterns.join(", ")}`:"Finding files";case "Execute":case "execute":let l=e.command||"";return l.length>60?`Running: ${l.substring(0,60)}...`:`Running: ${l}`;case "read_multiple_files":return e.files&&Array.isArray(e.files)?`Reading ${e.files.length} files`:"Reading multiple files";default:return `Executing ${a}`}}var uo=class{batchTimeWindow;activeBatches=new Map;pendingCalls=new Map;batchableTools=new Set(["readfile","write_file","create_file","list_directory","LS","Glob","find_files","read_multiple_files"]);constructor(e=200){this.batchTimeWindow=e;}detectBatch(e,t,s,n,r){if(!this.isBatchable(t))return {type:"single",merge:false};let i=this.pendingCalls.get(t)||[];if(i.length===0)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false};let o=i[i.length-1];if(r-o.startTime>this.batchTimeWindow)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false};if(i.some(u=>u.targetPath===s))return {type:"single",merge:false};if(i.length===1){let u=this.createBatch(o,e,s,r);return i.push({toolId:e,toolName:t,targetPath:s,startTime:r,args:n}),{type:"batch",merge:false,batchId:u,shouldCreateBatch:true}}else {let u=this.findActiveBatch(t);return u?(i.push({toolId:e,toolName:t,targetPath:s,startTime:r,args:n}),this.updateBatch(u,s,r),{type:"batch",merge:true,batchId:u}):(this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false})}}recordCompletion(e,t){let s=this.findActiveBatch(e);if(s){let n=this.activeBatches.get(s);n&&(n.completed++,n.completed>=n.total&&this.completeBatch(s));}}getBatchInfo(e){return this.activeBatches.get(e)}isBatchable(e){return this.batchableTools.has(e)}createBatch(e,t,s,n){let r=`batch-${e.toolName}-${n}`;return this.activeBatches.set(r,{batchId:r,toolName:e.toolName,targets:[e.targetPath,s],startTime:e.startTime,lastCallTime:n,completed:0,total:2}),r}updateBatch(e,t,s){let n=this.activeBatches.get(e);n&&(n.targets.push(t),n.total++,n.lastCallTime=s);}findActiveBatch(e){for(let[t,s]of this.activeBatches.entries())if(s.toolName===e)return t}completeBatch(e){this.activeBatches.delete(e);let t=this.activeBatches.get(e);t&&this.pendingCalls.delete(t.toolName);}cleanupExpiredBatches(e){let t=this.batchTimeWindow*5,s=[];this.activeBatches.forEach((r,i)=>{e-r.lastCallTime>t&&s.push(i);}),s.forEach(r=>this.completeBatch(r));let n=[];this.pendingCalls.forEach((r,i)=>{if(r.length>0){let o=r[r.length-1];e-o.startTime>t&&n.push(i);}}),n.forEach(r=>this.pendingCalls.delete(r));}reset(){this.activeBatches.clear(),this.pendingCalls.clear();}getStats(){let e=[];return this.activeBatches.forEach((t,s)=>{e.push({batchId:s,toolName:t.toolName,total:t.total,completed:t.completed});}),{activeBatches:this.activeBatches.size,pendingCalls:this.pendingCalls.size,batches:e}}};W();var Aw={default:["Thinking...","Processing...","Analyzing...","Pondering...","Contemplating..."]};var po={};function Ew(a,e,t=true){po[e]||(po[e]=0);let s=po[e]%a.length,n=a[s];return t&&(po[e]=(s+1)%a.length),n}function Xp(){let a=Aw.default;return Ew(a,"default")}function Qp(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 Zp(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 em(a,e,t){let s=pp(a,e,t),n=Gi(s);return {success:false,error:s.code,code:s.code,category:s.category,message:s.message,suggestion:n,retryable:s.retryable,receivedArgs:e?.substring(0,500)}}var mo=class{state="idle";lastStatusKey="";lastStatusAt=0;shouldEmit(e){if(e.type==="status"){let t=e.timestamp??Date.now(),s=`${e.status}:${e.message}`;if(s===this.lastStatusKey&&t-this.lastStatusAt<200)return false;this.lastStatusKey=s,this.lastStatusAt=t;}return this.transition(e),true}getState(){return this.state}transition(e){switch(e.type){case "thinking":case "reasoning":case "reasoning_complete":case "text":this.state="thinking";return;case "tool_call_start":this.state="tool_running";return;case "tool_call_end":case "tool_output":this.state="thinking";return;case "status":e.status==="tool_call"?this.state="tool_running":e.status==="thinking"?this.state="thinking":e.status==="complete"?this.state="completed":e.status==="error"&&(this.state="error");return;case "run_result":this.state="completed";return;case "error":case "error_classified":this.state="error";return;default:return}}};var sm=12e3,go=class{runner;memory;sessionManager;sessionSync;session;sessionEnabled;memoryPressure;compatProfile;workDir;model;systemPrompt;sandboxSetter;llmProvider;sessionSeed;sessionTotalInputTokens=0;sessionTotalOutputTokens=0;lastMemoryPressureState="unknown";autoCompactionInProgress=false;isRunning=false;shouldInterrupt=false;abortController=null;interruptResolver=null;interruptPromise=null;compressionMode="sync";eventEmitter=new EventEmitter;eventSequence=0;hostStateMachine=new mo;descriptionExtractor=new lo;commandGenerator=new co;lastAssistantMessage="";batchDetector=new uo;toolCallIdCounter=0;recentToolCalls=new Map;currentTaskMetadata;pendingInjectedMessages=[];constructor(e){this.runner=e.runner,this.memory=e.memory,this.sessionManager=e.sessionManager,this.sessionSync=e.sessionSync,this.session=e.session,this.sessionEnabled=e.sessionEnabled??true,this.workDir=te__default.resolve(e.workDir),this.model=e.model,this.systemPrompt=e.systemPrompt,this.memoryPressure=e.memoryPressure,this.compatProfile=e.compatProfile,this.sandboxSetter=e.setSandboxMode,this.llmProvider=e.llmProvider,this.sessionSeed=randomBytes(16).toString("hex"),this.syncWorkspaceEnv(),this.applyAnthropicSessionUserId();}on(e){return this.eventEmitter.on("event",e),()=>this.eventEmitter.off("event",e)}setWorkDir(e){this.workDir=te__default.resolve(e),this.syncWorkspaceEnv();}setSession(e,t){this.session=e||void 0,this.sessionSync=t,this.applyAnthropicSessionUserId();}applyAnthropicSessionUserId(){let t=this.llmProvider?.getProvider?.();if(!t||typeof t.setUserId!="function")return;let s=this.session?.sessionId,n=Pu(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(`
1818
1818
  `).map(f=>f.trim()).find(f=>f.length>0);return p(g?g.replace(/^\*\s*/,""):l||"branch info")}case "readfile":case "Read":case "read_file":case "smart_read":case "read":return `${p(d)} \u2014 ${h} lines read`;case "search":case "Grep":case "grep":{let g=t?.pattern||t?.query||"",f=(s.match(/\n/g)||[]).length;return `"${p(g,30)}" \u2014 ${f} matches`}case "search_files":case "Glob":case "glob":case "find_files":{let g=t?.pattern||t?.glob||"",f=h;return `"${p(g,30)}" \u2014 ${f} files`}case "write_file":case "Write":case "edit_file":case "Edit":case "file_update":case "apply_patch":return `${p(d)} \u2713`;case "delete_file":return `deleted ${p(d)}`;case "rename_file":return `renamed \u2192 ${p(t?.new_path||t?.destination||"")}`;case "create_directory":return `created ${p(d||t?.directory||"")}`;case "command_exec":case "Bash":case "bash":case "shell":case "execute_command":case "execute_shell":{let g=t?.command||"",f=s.trim().split(`
@@ -1860,9 +1860,9 @@ ${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 Mw="ark.cn-beijing.volces.com";function Pw(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 Ol(a){return a.includes("doubao-seed")}function Nl(a){return !!a&&a.includes(Mw)}function Dw(a){let e=a?.getProvider?.();return e instanceof Vt?e:void 0}function Lw(a){let e=a?.getProvider?.();return e instanceof bn?e:void 0}function Ow(a){let e=a?.getProvider?.();return e instanceof vn?e:void 0}function Nw(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&&Nl(t)&&Ol(e);return (n||r||l)&&(o.setThinkingMode=u=>{if(r&&r.setThinking({type:u}),l&&s&&s.setDoubaoThinking({type:u}),n){let d=u==="auto"?"enabled":u;n.setThinking({type:d});}}),o}function ho(a){let{provider:e,model:t,sessionId:s}=a,n=e.protocol,r=e.models?.find(h=>h.name===t),i=e.baseUrl||void 0,o,l,c,u,d;if(n==="openai"||n==="openai-responses"||n==="kimi"){let h={...e,defaultModel:t,lastSelectedModel:t,apiEndpoint:e.urlSuffix,sessionId:s,modelConfig:r,doubaoThinking:Nl(i)&&Ol(t)?{type:"enabled"}:void 0},g=Ot.createAdapter(n,h);o=g,l=Dw(g),l&&Nl(i)&&Ol(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,c=Lw(g),c&&Pw(t)&&c.setThinking({type:"enabled"});}else if(n==="anthropic-openai"){let h=e.urlSuffix||"/v1/messages",g={apiKey:e.apiKey,baseUrl:i,defaultModel:t,apiEndpoint:h,streamFormat:"anthropic",sessionId:s,retry:e.retry,modelConfig:r};l=new Vt(g),o=l;}else if(n==="doubao")u=new ao({apiKey:e.apiKey,baseUrl:i,defaultModel:t,thinking:{type:"enabled"},retry:e.retry}),o=u;else if(n==="gemini"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,d=Ow(g);}else throw new Error(`Unsupported provider protocol: ${n}`);let p=Nw({model:t,baseUrl:i,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:d});return {llmProvider:o,controls:p}}function nm(a){return new Vi({llmProvider:a.llmProvider,model:a.model,tools:a.tools,memory:a.memory,config:a.config,agentName:a.agentName,agentDescription:a.agentDescription,instructions:a.instructions,contextInjection:a.contextInjection,plannerMode:a.plannerMode,structuredOutput:a.structuredOutput,providerName:a.providerName,contextWindow:a.contextWindow,tailTokenBudget:a.tailTokenBudget,maxInputTokensOverride:a.maxInputTokensOverride,toolInputGuardrails:a.toolInputGuardrails??Lp,toolOutputGuardrails:a.toolOutputGuardrails??Op,compressionMode:a.compressionMode,workspacePath:a.workspacePath,permissionManager:a.permissionManager,disableSystemPrompt:a.disableSystemPrompt,enableFGTS:a.enableFGTS})}function rm(a){return new go({runner:a.runner,memory:a.memory,sessionManager:a.sessionManager||new Qt,sessionEnabled:a.sessionEnabled??false,workDir:a.workDir,model:a.model,memoryPressure:a.memoryPressure,compatProfile:a.compatProfile,systemPrompt:a.systemPrompt,setSandboxMode:a.setSandboxMode,llmProvider:a.llmProvider})}function fo(a){return new at(a)}W();async function im(a){let{sessionId:e,provider:t,llmConfig:s,workspacePath:n,workDir:r,instructions:i,systemPrompt:o,agentName:l,agentDescription:c,permissionManager:u,tools:d,memory:p,memorySize:h,agentConfig:g,contextInjection:f,plannerMode:b,structuredOutput:y,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,platformServices:T,sessionManager:_,sessionEnabled:M,disableSystemPrompt:F,enableFGTS:x}=a,R=p??fo(h??50),j=typeof i=="string"?i:"[Function]";m.info("HOST_FACTORY",`Creating host with instructions length: ${j.length}`),m.info("HOST_FACTORY",`instructions contains \u534F\u4F5C\u6A21\u5F0F: ${j.includes("\u534F\u4F5C\u6A21\u5F0F")}`),m.info("HOST_FACTORY",`instructions contains delegate_task: ${j.includes("delegate_task")}`),m.debug("HOST_FACTORY",`instructions preview: ${j.substring(0,300)}`);let{llmProvider:v,controls:E}=ho({provider:t,model:s.model,sessionId:e}),L=s.compatProfile??null,I=L?new Hr(L):void 0,A=d??await un(n,T),O=g??{maxIterations:0,temperature:.7},$=nm({llmProvider:v,model:s.model,tools:A,memory:R,config:O,agentName:l,agentDescription:c,instructions:i,contextInjection:f,plannerMode:b,structuredOutput:y,providerName:s.providerName,contextWindow:L?.contextWindow,tailTokenBudget:L?.tailTokenBudget,maxInputTokensOverride:s.maxInputTokens,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,workspacePath:n,permissionManager:u,disableSystemPrompt:F,enableFGTS:x});return {host:rm({runner:$,memory:R,sessionManager:_??new Qt,sessionEnabled:M??false,workDir:r,model:s.model,memoryPressure:I,compatProfile:L,systemPrompt:o??(typeof i=="string"?i:""),llmProvider:v}),controls:E,llmProvider:v,runner:$,memory:R}}var Nt=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new qr;}setWorkspace(e){this.hostController.setWorkspace(e);}getHost(e){return this.hostController.getHost(e)}hasHost(e){return this.hostController.hasHost(e)}clearHost(e){this.hostController.clearHost(e);}clearAll(){this.hostController.clearAll();}forEachHost(e){this.hostController.forEachHost(e);}async getOrCreateHost(e){let{sessionId:t,configKey:s,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R,onHostCreated:j}=e;return this.hostController.getOrCreateHost({sessionId:t,configKey:s,createHost:async()=>{let{host:v,controls:E,llmProvider:L,runner:I,memory:A}=await im({sessionId:t,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,platformServices:this.platformServices,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R});return j?.({host:v,controls:E,llmProvider:L,runner:I,memory:A}),v}})}async runTask(e){let{prompt:t,metadata:s,abortSignal:n,onHostReady:r,onEvent:i,...o}=e,l=await this.getOrCreateHost(o);r?.(l);let c=i?l.on(i):void 0;try{return await l.runTask(t,{metadata:s,abortSignal:n})}finally{c&&c();}}};async function om(a){let e=a.initialProviderId,t=a.initialModelName,s=a.routeConfig,n=0,r=null,i=s?s.routes.filter(o=>o.enabled).length:a.resolvedRoute?.fallbackChain.length??1;for(;;)try{return await a.runAttempt({providerId:e,modelName:t,routeConfig:s,attempt:n,isRetry:n>0,previousError:r})}catch(o){let l=o instanceof Error?o:new Error(String(o));if(r=l,a.modelRouter&&e&&a.modelRouter.recordFailure(e,l),!!!(a.autoFailover&&a.resolvedRoute&&a.fallbackDecider&&a.modelAlias&&e))throw l;let u=a.fallbackDecider.shouldFallback(a.modelAlias,e,l,a.resolvedRoute.fallbackChain);if(u.shouldFallback&&u.targetProvider&&u.event){if(a.fallbackDecider.executeFallback(u),n+=1,e=u.targetProvider.providerId,t=u.targetProvider.modelName,s&&(s={...s,routes:s.routes.filter(d=>d.providerId!==u.event.fromProviderId)}),a.onRetry?.({providerId:e,modelName:t,attempt:n,decision:u}),n>=i)throw a.onExhausted?.("All providers have failed. Please try again later."),l;continue}throw u.exhausted&&a.onExhausted?.(u.reason),l}}W();var _r=240,yo=2e3;function Rt(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var $l=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},$t=class{hostService;checkpointService;resolveProvider;actionLog;constructor(e){this.hostService=e.hostService,this.checkpointService=e.checkpointService,this.resolveProvider=e.resolveProvider,this.actionLog=e.actionLog;}async runSession(e){let{sessionId:t,prompt:s,metadata:n,startedAt:r=Date.now(),isAutoRouted:i,routeConfig:o,modelRouter:l,fallbackDecider:c,eventHub:u,abortSignal:d,buildHostConfig:p,onHostReady:h,onRuntimeEvent:g,onStatus:f,onRouteResolved:b,onRetry:y}=e,w=e.providerId,C=e.modelName,k=null,T=this.actionLog?.createRunId();if(this.actionLog){let F=Rt(s,_r);this.actionLog.record({type:"run_start",sessionId:t,runId:T,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:Rt(s,yo),promptLength:s.length,attachments:n?.attachments?.map(x=>({type:x.type,name:x.name,path:x.path}))}});}i&&o&&l&&(k=l.resolveProvider(o.modelAlias),k&&(w=k.providerId,C=k.modelName,b?.(k),k.degraded&&f?.("warning",`Using degraded provider: ${w}`)));let _=n;if(this.checkpointService)try{await this.checkpointService.startMessage(t);}catch{f?.("warning","Checkpoint start failed");}let M=false;try{let F=await om({modelAlias:o?.modelAlias,initialProviderId:w,initialModelName:C,routeConfig:o,resolvedRoute:k,fallbackDecider:c,modelRouter:l??void 0,autoFailover:o?.autoFailover===!0,onRetry:({decision:x})=>{this.actionLog&&this.actionLog.record({type:"status",sessionId:t,runId:T,actor:"system",summary:x?.event?`Fallback: ${x.event.fromProviderId} -> ${x.event.toProviderId}`:"Fallback: switching provider",data:{from:x?.event?.fromProviderId,to:x?.event?.toProviderId,reason:x?.reason}}),y?.(x);},onExhausted:x=>{f?.("error",`All providers exhausted: ${x}`),this.actionLog&&this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`All providers exhausted: ${Rt(x,_r)}`,data:{reason:x}});},runAttempt:async x=>{let R=this.resolveProvider(x.providerId,x.modelName);if(!R.provider||!R.llmConfig)throw new $l("No provider configured. Please add an API provider first.");f?.("info",`Connecting to ${R.llmConfig.model}...`),this.actionLog&&this.actionLog.record({type:"run_attempt",sessionId:t,runId:T,actor:"system",summary:x.isRetry?`Retry ${x.attempt}: ${R.llmConfig.model}`:`Run: ${R.llmConfig.model}`,data:{providerId:R.provider.id,providerName:R.llmConfig.providerName,model:R.llmConfig.model,attempt:x.attempt,isRetry:x.isRetry,previousError:x.previousError?.message}});let j=p(R.provider,R.llmConfig),v={contextUsed:0,startTime:Date.now(),provider:R.llmConfig.providerName||R.provider.id||"unknown",model:R.llmConfig.model};return {summary:await this.hostService.runTask({...j,prompt:s,metadata:_,abortSignal:d,onHostReady:h,onEvent:L=>{if(L.type==="tool_call_end"&&m.info("ORCHESTRATOR",`\u{1F525} onEvent received tool_call_end: name=${L.name} toolId=${L.toolId}`),this.actionLog){let I=this.buildActionLogEntry(L,t,T);I&&this.actionLog.record(I);}u?.emit(t,L,v),g?.(L,v);}}),contextUsed:v.contextUsed,providerId:R.provider.id}}});if(k&&F.providerId&&l){let x=Date.now()-r;l.recordSuccess(F.providerId,x),c&&c.recordSuccess(F.providerId);}if(this.checkpointService)try{await this.checkpointService.finishMessage(t,"Message completed"),M=!0;}catch{f?.("warning","Checkpoint save failed");}return {summary:F.summary,contextUsed:F.contextUsed,providerId:F.providerId}}catch(F){if(this.actionLog){let x=F instanceof Error?F.message:String(F);this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`Run error: ${Rt(x,_r)}`,data:{message:x}});}throw F}finally{if(this.checkpointService&&!M)try{await this.checkpointService.stopWatching();}catch{f?.("warning","Checkpoint cleanup failed");}}}buildActionLogEntry(e,t,s){if(!this.actionLog)return null;let n=r=>this.actionLog?.formatFilePath(r)??r;switch(e.type){case "tool_call_start":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool start: ${e.name} (${r})`:`Tool start: ${e.name}`,o=e.args?Rt(JSON.stringify(e.args),yo):void 0;return {type:"tool_call_start",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,toolId:e.toolId,batchId:e.batchId,targetPath:r,description:e.description,equivalentCommand:e.equivalentCommand,argsPreview:o}}}case "tool_call_end":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool ${e.success?"done":"failed"}: ${e.name} (${r})`:`Tool ${e.success?"done":"failed"}: ${e.name}`,o=e.output?Rt(e.output,yo):void 0;return {type:"tool_call_end",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,success:e.success,duration:e.duration,resultLength:e.resultLength,summary:e.summary,outputPreview:o,outputTruncated:e.outputTruncated,toolId:e.toolId,batchId:e.batchId,targetPath:r}}}case "file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=e.additions||e.removals?`File updated: ${r} (+${e.additions??0}/-${e.removals??0})`:`File updated: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,additions:e.additions,removals:e.removals,description:e.description,contentLength:e.content?.length??0}}}case "edit_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File edited: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,startLine:e.startLine,hunks:e.hunks?.length??0,oldPreview:Rt(e.oldString,200),newPreview:Rt(e.newString,200),description:e.description}}}case "write_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File written: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,contentLength:e.content?.length??0,description:e.description}}}case "checkpoint":return {type:"checkpoint",sessionId:t,runId:s,actor:"system",summary:`Checkpoint saved: ${e.id}`,data:{id:e.id,auto:e.auto}};case "plan_update":{let r=e.plan.length,i=e.plan.filter(c=>c.status==="completed").length,o=e.plan.filter(c=>c.status==="in_progress").length,l=r-i-o;return {type:"plan_update",sessionId:t,runId:s,actor:"assistant",summary:`Plan update: ${i} done, ${o} active, ${l} pending`,data:{explanation:e.explanation,plan:e.plan}}}case "context_compaction":return {type:"context_compaction",sessionId:t,runId:s,actor:"system",summary:`Context compacted: ${e.originalTokens} -> ${e.finalTokens} tokens`,data:{originalMessages:e.originalMessages,keptMessages:e.keptMessages,droppedMessages:e.droppedMessages,compressedMessages:e.compressedMessages,originalTokens:e.originalTokens,finalTokens:e.finalTokens,budgetTokens:e.budgetTokens,useLLM:e.useLLM}};case "stream_retry":return {type:"stream_retry",sessionId:t,runId:s,actor:"system",summary:`Stream retry ${e.attempt}/${e.maxRetries}: ${e.errorCode}`,data:{error:e.error,errorCode:e.errorCode,attempt:e.attempt,maxRetries:e.maxRetries,delayMs:e.delayMs}};case "stream_recovered":return {type:"stream_recovered",sessionId:t,runId:s,actor:"system",summary:`Stream recovered (attempt ${e.attempt})`,data:{attempt:e.attempt,maxRetries:e.maxRetries}};case "run_result":return {type:"run_result",sessionId:t,runId:s,actor:"assistant",summary:`Run completed in ${e.durationMs}ms, tokens ${e.totalTokens}`,data:{outputPreview:Rt(e.output,yo),totalTokens:e.totalTokens,iterations:e.iterations,toolCalls:e.toolCalls,durationMs:e.durationMs}};case "error":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Runtime error: ${Rt(e.message,_r)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${Rt(e.message,_r)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};W();function Fl(a){let e=a.getAll();if(e.length===0)return "";let t=[],s=0,n=12e3;for(let r=e.length-1;r>=0&&!(s>=n);r--){let i=e[r];if(i.role==="tool")continue;let l=(typeof i.content=="string"?i.content:JSON.stringify(i.content)).substring(0,1e3);t.unshift(`[${i.role}]: ${l}`),s+=l.length;}return t.join(`
1863
+ \u51C0\u8282\u7701: ${x(F.totalTokens)}`;}this.emitCompacting("\u2713 LLM \u538B\u7F29\u5B8C\u6210",T);}else this.emitCompacting("\u2139 \u65E0\u9700\u538B\u7F29","Context \u4F7F\u7528\u91CF\u5728\u9884\u7B97\u8303\u56F4\u5185");}catch(f){throw this.emitLog("error","\u274C LLM \u538B\u7F29\u5931\u8D25",f?.message||String(f)),f}}setSandboxMode(e){this.sandboxSetter?.(e);}setApprovalHandler(e){this.runner.setApprovalHandler(e);}setMode(e){this.runner.setMode(e);}setConversationHistory(e){this.memory.clear(),this.systemPrompt&&this.memory.add({role:"system",content:this.systemPrompt});for(let t of e)!t||!t.content||this.memory.add({role:t.role,content:t.content,name:t.name,tool_calls:t.tool_calls});}dispose(){this.isRunning&&this.interrupt(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.eventEmitter.removeAllListeners(),this.memory.clear(),this.recentToolCalls.clear(),this.batchDetector.reset(),console.log("[AgentRuntimeHost] Disposed");}};var 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 Ol(a){return a.includes("doubao-seed")}function Nl(a){return !!a&&a.includes(Pw)}function Lw(a){let e=a?.getProvider?.();return e instanceof Vt?e:void 0}function Ow(a){let e=a?.getProvider?.();return e instanceof bn?e:void 0}function Nw(a){let e=a?.getProvider?.();return e instanceof vn?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&&Nl(t)&&Ol(e);return (n||r||l)&&(o.setThinkingMode=u=>{if(r&&r.setThinking({type:u}),l&&s&&s.setDoubaoThinking({type:u}),n){let d=u==="auto"?"enabled":u;n.setThinking({type:d});}}),o}function ho(a){let{provider:e,model:t,sessionId:s}=a,n=e.protocol,r=e.models?.find(h=>h.name===t),i=e.baseUrl||void 0,o,l,c,u,d;if(n==="openai"||n==="openai-responses"||n==="kimi"){let h={...e,defaultModel:t,lastSelectedModel:t,apiEndpoint:e.urlSuffix,sessionId:s,modelConfig:r,doubaoThinking:Nl(i)&&Ol(t)?{type:"enabled"}:void 0},g=Ot.createAdapter(n,h);o=g,l=Lw(g),l&&Nl(i)&&Ol(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,c=Ow(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 ao({apiKey:e.apiKey,baseUrl:i,defaultModel:t,thinking:{type:"enabled"},retry:e.retry}),o=u;else if(n==="gemini"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,d=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 nm(a){return new Vi({llmProvider:a.llmProvider,model:a.model,tools:a.tools,memory:a.memory,config:a.config,agentName:a.agentName,agentDescription:a.agentDescription,instructions:a.instructions,contextInjection:a.contextInjection,plannerMode:a.plannerMode,structuredOutput:a.structuredOutput,providerName:a.providerName,contextWindow:a.contextWindow,tailTokenBudget:a.tailTokenBudget,maxInputTokensOverride:a.maxInputTokensOverride,toolInputGuardrails:a.toolInputGuardrails??Lp,toolOutputGuardrails:a.toolOutputGuardrails??Op,compressionMode:a.compressionMode,workspacePath:a.workspacePath,permissionManager:a.permissionManager,disableSystemPrompt:a.disableSystemPrompt,enableFGTS:a.enableFGTS})}function rm(a){return new go({runner:a.runner,memory:a.memory,sessionManager:a.sessionManager||new Qt,sessionEnabled:a.sessionEnabled??false,workDir:a.workDir,model:a.model,memoryPressure:a.memoryPressure,compatProfile:a.compatProfile,systemPrompt:a.systemPrompt,setSandboxMode:a.setSandboxMode,llmProvider:a.llmProvider})}function fo(a){return new at(a)}W();async function im(a){let{sessionId:e,provider:t,llmConfig:s,workspacePath:n,workDir:r,instructions:i,systemPrompt:o,agentName:l,agentDescription:c,permissionManager:u,tools:d,memory:p,memorySize:h,agentConfig:g,contextInjection:f,plannerMode:b,structuredOutput:y,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,platformServices:T,sessionManager:_,sessionEnabled:M,disableSystemPrompt:F,enableFGTS:x}=a,R=p??fo(h??50),j=typeof i=="string"?i:"[Function]";m.info("HOST_FACTORY",`Creating host with instructions length: ${j.length}`),m.info("HOST_FACTORY",`instructions contains \u534F\u4F5C\u6A21\u5F0F: ${j.includes("\u534F\u4F5C\u6A21\u5F0F")}`),m.info("HOST_FACTORY",`instructions contains delegate_task: ${j.includes("delegate_task")}`),m.debug("HOST_FACTORY",`instructions preview: ${j.substring(0,300)}`);let{llmProvider:v,controls:E}=ho({provider:t,model:s.model,sessionId:e}),L=s.compatProfile??null,I=L?new Hr(L):void 0,A=d??await un(n,T),O=g??{maxIterations:0,temperature:.7},$=nm({llmProvider:v,model:s.model,tools:A,memory:R,config:O,agentName:l,agentDescription:c,instructions:i,contextInjection:f,plannerMode:b,structuredOutput:y,providerName:s.providerName,contextWindow:L?.contextWindow,tailTokenBudget:L?.tailTokenBudget,maxInputTokensOverride:s.maxInputTokens,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,workspacePath:n,permissionManager:u,disableSystemPrompt:F,enableFGTS:x});return {host:rm({runner:$,memory:R,sessionManager:_??new Qt,sessionEnabled:M??false,workDir:r,model:s.model,memoryPressure:I,compatProfile:L,systemPrompt:o??(typeof i=="string"?i:""),llmProvider:v}),controls:E,llmProvider:v,runner:$,memory:R}}var Nt=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new qr;}setWorkspace(e){this.hostController.setWorkspace(e);}getHost(e){return this.hostController.getHost(e)}hasHost(e){return this.hostController.hasHost(e)}clearHost(e){this.hostController.clearHost(e);}clearAll(){this.hostController.clearAll();}forEachHost(e){this.hostController.forEachHost(e);}async getOrCreateHost(e){let{sessionId:t,configKey:s,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R,onHostCreated:j}=e;return this.hostController.getOrCreateHost({sessionId:t,configKey:s,createHost:async()=>{let{host:v,controls:E,llmProvider:L,runner:I,memory:A}=await im({sessionId:t,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,platformServices:this.platformServices,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R});return j?.({host:v,controls:E,llmProvider:L,runner:I,memory:A}),v}})}async runTask(e){let{prompt:t,metadata:s,abortSignal:n,onHostReady:r,onEvent:i,...o}=e,l=await this.getOrCreateHost(o);r?.(l);let c=i?l.on(i):void 0;try{return await l.runTask(t,{metadata:s,abortSignal:n})}finally{c&&c();}}};async function om(a){let e=a.initialProviderId,t=a.initialModelName,s=a.routeConfig,n=0,r=null,i=s?s.routes.filter(o=>o.enabled).length:a.resolvedRoute?.fallbackChain.length??1;for(;;)try{return await a.runAttempt({providerId:e,modelName:t,routeConfig:s,attempt:n,isRetry:n>0,previousError:r})}catch(o){let l=o instanceof Error?o:new Error(String(o));if(r=l,a.modelRouter&&e&&a.modelRouter.recordFailure(e,l),!!!(a.autoFailover&&a.resolvedRoute&&a.fallbackDecider&&a.modelAlias&&e))throw l;let u=a.fallbackDecider.shouldFallback(a.modelAlias,e,l,a.resolvedRoute.fallbackChain);if(u.shouldFallback&&u.targetProvider&&u.event){if(a.fallbackDecider.executeFallback(u),n+=1,e=u.targetProvider.providerId,t=u.targetProvider.modelName,s&&(s={...s,routes:s.routes.filter(d=>d.providerId!==u.event.fromProviderId)}),a.onRetry?.({providerId:e,modelName:t,attempt:n,decision:u}),n>=i)throw a.onExhausted?.("All providers have failed. Please try again later."),l;continue}throw u.exhausted&&a.onExhausted?.(u.reason),l}}W();var _r=240,yo=2e3;function Rt(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var $l=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},$t=class{hostService;checkpointService;resolveProvider;actionLog;constructor(e){this.hostService=e.hostService,this.checkpointService=e.checkpointService,this.resolveProvider=e.resolveProvider,this.actionLog=e.actionLog;}async runSession(e){let{sessionId:t,prompt:s,metadata:n,startedAt:r=Date.now(),isAutoRouted:i,routeConfig:o,modelRouter:l,fallbackDecider:c,eventHub:u,abortSignal:d,buildHostConfig:p,onHostReady:h,onRuntimeEvent:g,onStatus:f,onRouteResolved:b,onRetry:y}=e,w=e.providerId,C=e.modelName,k=null,T=this.actionLog?.createRunId();if(this.actionLog){let F=Rt(s,_r);this.actionLog.record({type:"run_start",sessionId:t,runId:T,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:Rt(s,yo),promptLength:s.length,attachments:n?.attachments?.map(x=>({type:x.type,name:x.name,path:x.path}))}});}i&&o&&l&&(k=l.resolveProvider(o.modelAlias),k&&(w=k.providerId,C=k.modelName,b?.(k),k.degraded&&f?.("warning",`Using degraded provider: ${w}`)));let _=n;if(this.checkpointService)try{await this.checkpointService.startMessage(t);}catch{f?.("warning","Checkpoint start failed");}let M=false;try{let F=await om({modelAlias:o?.modelAlias,initialProviderId:w,initialModelName:C,routeConfig:o,resolvedRoute:k,fallbackDecider:c,modelRouter:l??void 0,autoFailover:o?.autoFailover===!0,onRetry:({decision:x})=>{this.actionLog&&this.actionLog.record({type:"status",sessionId:t,runId:T,actor:"system",summary:x?.event?`Fallback: ${x.event.fromProviderId} -> ${x.event.toProviderId}`:"Fallback: switching provider",data:{from:x?.event?.fromProviderId,to:x?.event?.toProviderId,reason:x?.reason}}),y?.(x);},onExhausted:x=>{f?.("error",`All providers exhausted: ${x}`),this.actionLog&&this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`All providers exhausted: ${Rt(x,_r)}`,data:{reason:x}});},runAttempt:async x=>{let R=this.resolveProvider(x.providerId,x.modelName);if(!R.provider||!R.llmConfig)throw new $l("No provider configured. Please add an API provider first.");f?.("info",`Connecting to ${R.llmConfig.model}...`),this.actionLog&&this.actionLog.record({type:"run_attempt",sessionId:t,runId:T,actor:"system",summary:x.isRetry?`Retry ${x.attempt}: ${R.llmConfig.model}`:`Run: ${R.llmConfig.model}`,data:{providerId:R.provider.id,providerName:R.llmConfig.providerName,model:R.llmConfig.model,attempt:x.attempt,isRetry:x.isRetry,previousError:x.previousError?.message}});let j=p(R.provider,R.llmConfig),v={contextUsed:0,startTime:Date.now(),provider:R.llmConfig.providerName||R.provider.id||"unknown",model:R.llmConfig.model};return {summary:await this.hostService.runTask({...j,prompt:s,metadata:_,abortSignal:d,onHostReady:h,onEvent:L=>{if(L.type==="tool_call_end"&&m.info("ORCHESTRATOR",`\u{1F525} onEvent received tool_call_end: name=${L.name} toolId=${L.toolId}`),this.actionLog){let I=this.buildActionLogEntry(L,t,T);I&&this.actionLog.record(I);}u?.emit(t,L,v),g?.(L,v);}}),contextUsed:v.contextUsed,providerId:R.provider.id}}});if(k&&F.providerId&&l){let x=Date.now()-r;l.recordSuccess(F.providerId,x),c&&c.recordSuccess(F.providerId);}if(this.checkpointService)try{await this.checkpointService.finishMessage(t,"Message completed"),M=!0;}catch{f?.("warning","Checkpoint save failed");}return {summary:F.summary,contextUsed:F.contextUsed,providerId:F.providerId}}catch(F){if(this.actionLog){let x=F instanceof Error?F.message:String(F);this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`Run error: ${Rt(x,_r)}`,data:{message:x}});}throw F}finally{if(this.checkpointService&&!M)try{await this.checkpointService.stopWatching();}catch{f?.("warning","Checkpoint cleanup failed");}}}buildActionLogEntry(e,t,s){if(!this.actionLog)return null;let n=r=>this.actionLog?.formatFilePath(r)??r;switch(e.type){case "tool_call_start":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool start: ${e.name} (${r})`:`Tool start: ${e.name}`,o=e.args?Rt(JSON.stringify(e.args),yo):void 0;return {type:"tool_call_start",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,toolId:e.toolId,batchId:e.batchId,targetPath:r,description:e.description,equivalentCommand:e.equivalentCommand,argsPreview:o}}}case "tool_call_end":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool ${e.success?"done":"failed"}: ${e.name} (${r})`:`Tool ${e.success?"done":"failed"}: ${e.name}`,o=e.output?Rt(e.output,yo):void 0;return {type:"tool_call_end",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,success:e.success,duration:e.duration,resultLength:e.resultLength,summary:e.summary,outputPreview:o,outputTruncated:e.outputTruncated,toolId:e.toolId,batchId:e.batchId,targetPath:r}}}case "file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=e.additions||e.removals?`File updated: ${r} (+${e.additions??0}/-${e.removals??0})`:`File updated: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,additions:e.additions,removals:e.removals,description:e.description,contentLength:e.content?.length??0}}}case "edit_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File edited: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,startLine:e.startLine,hunks:e.hunks?.length??0,oldPreview:Rt(e.oldString,200),newPreview:Rt(e.newString,200),description:e.description}}}case "write_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File written: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,contentLength:e.content?.length??0,description:e.description}}}case "checkpoint":return {type:"checkpoint",sessionId:t,runId:s,actor:"system",summary:`Checkpoint saved: ${e.id}`,data:{id:e.id,auto:e.auto}};case "plan_update":{let r=e.plan.length,i=e.plan.filter(c=>c.status==="completed").length,o=e.plan.filter(c=>c.status==="in_progress").length,l=r-i-o;return {type:"plan_update",sessionId:t,runId:s,actor:"assistant",summary:`Plan update: ${i} done, ${o} active, ${l} pending`,data:{explanation:e.explanation,plan:e.plan}}}case "context_compaction":return {type:"context_compaction",sessionId:t,runId:s,actor:"system",summary:`Context compacted: ${e.originalTokens} -> ${e.finalTokens} tokens`,data:{originalMessages:e.originalMessages,keptMessages:e.keptMessages,droppedMessages:e.droppedMessages,compressedMessages:e.compressedMessages,originalTokens:e.originalTokens,finalTokens:e.finalTokens,budgetTokens:e.budgetTokens,useLLM:e.useLLM}};case "stream_retry":return {type:"stream_retry",sessionId:t,runId:s,actor:"system",summary:`Stream retry ${e.attempt}/${e.maxRetries}: ${e.errorCode}`,data:{error:e.error,errorCode:e.errorCode,attempt:e.attempt,maxRetries:e.maxRetries,delayMs:e.delayMs}};case "stream_recovered":return {type:"stream_recovered",sessionId:t,runId:s,actor:"system",summary:`Stream recovered (attempt ${e.attempt})`,data:{attempt:e.attempt,maxRetries:e.maxRetries}};case "run_result":return {type:"run_result",sessionId:t,runId:s,actor:"assistant",summary:`Run completed in ${e.durationMs}ms, tokens ${e.totalTokens}`,data:{outputPreview:Rt(e.output,yo),totalTokens:e.totalTokens,iterations:e.iterations,toolCalls:e.toolCalls,durationMs:e.durationMs}};case "error":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Runtime error: ${Rt(e.message,_r)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${Rt(e.message,_r)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};W();function Fl(a){let e=a.getAll();if(e.length===0)return "";let t=[],s=0,n=12e3;for(let r=e.length-1;r>=0&&!(s>=n);r--){let i=e[r];if(i.role==="tool")continue;let l=(typeof i.content=="string"?i.content:JSON.stringify(i.content)).substring(0,1e3);t.unshift(`[${i.role}]: ${l}`),s+=l.length;}return t.join(`
1864
1864
 
1865
- `)}W();var $w=new Set(["search_files","search","grep","list_directory","show_tree","smart_tree","git_status","git_diff","git_log","smart_read","readfile","read","execute_shell"]);function Bl(a){return [Fw(a)]}var Gl=`
1865
+ `)}W();var Fw=new Set(["search_files","search","grep","list_directory","show_tree","smart_tree","git_status","git_diff","git_log","smart_read","readfile","read","execute_shell"]);function Bl(a){return [jw(a)]}var Gl=`
1866
1866
  ## \u5B50 Agent \u5DE5\u5177
1867
1867
 
1868
1868
  \u4F60\u6709 explore \u5185\u7F6E\u5DE5\u5177\uFF0C\u5B50 agent \u80FD\u770B\u5230\u5F53\u524D\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u3002
@@ -1907,7 +1907,7 @@ explore \u7684 prompt \u8981\u5199\u5F97\u5177\u4F53\u3001\u6709\u8FB9\u754C\uFF
1907
1907
 
1908
1908
  \u793A\u4F8B\uFF1A
1909
1909
  ask_user({ questions: [{ question: "\u6570\u636E\u5E93\u7528\u54EA\u4E2A\uFF1F", options: [{ label: "PostgreSQL", description: "\u5173\u7CFB\u578B\uFF0C\u9002\u5408\u590D\u6742\u67E5\u8BE2" }, { label: "MongoDB", description: "\u6587\u6863\u578B\uFF0Cschema \u7075\u6D3B" }] }] })
1910
- `,jl=3;function Fw(a){let e=0,t=async(s,n)=>{let r=a.allTools.filter(c=>$w.has(c.name)),i=Fl(a.getParentMemory()),o=new at,l=jw(a.workDir,i,s);if(m.info("SINGLE_EXPLORE",`${n} started`,{prompt:s.substring(0,80),toolCount:r.length}),a.abortSignal?.aborted)return {id:n,prompt:s,output:"",error:"aborted before start"};try{let c=`explore_${n}_${Date.now()}`,u=await a.orchestrator.runSession({sessionId:c,prompt:s,providerId:a.providerId,modelName:a.modelName,abortSignal:a.abortSignal,buildHostConfig:(d,p)=>({sessionId:c,configKey:`explore_${n}`,provider:d,llmConfig:p,workspacePath:a.workDir,workDir:a.workDir,instructions:l,systemPrompt:l,agentName:n,agentDescription:"Read-only codebase explorer",permissionManager:a.permissionManager,tools:r,memory:o,agentConfig:{temperature:.2,mode:"auto",maxIterations:30,maxRuntimeMs:300*1e3},sessionEnabled:!1,disableSystemPrompt:!0}),onRuntimeEvent:a.onSubAgentEvent?(d,p)=>a.onSubAgentEvent(n,{...d,workerRole:"Explore",workerTask:s.substring(0,60)},p):void 0});return m.info("SINGLE_EXPLORE",`${n} completed`,{output:(u.summary.output||"").substring(0,200)}),{id:n,prompt:s,output:u.summary.output||"(no output)"}}catch(c){return c.name==="AbortError"||a.abortSignal?.aborted?{id:n,prompt:s,output:"",error:"aborted"}:(m.error("SINGLE_EXPLORE",`${n} failed`,{error:c.message}),{id:n,prompt:s,output:"",error:c.message})}};return {name:"explore",description:`\u6D3E\u9063\u53EA\u8BFB\u5B50 agent \u63A2\u7D22\u4EE3\u7801\u5E93\u3002\u5B50 agent \u80FD\u770B\u5230\u5F53\u524D\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u3002
1910
+ `,jl=3;function jw(a){let e=0,t=async(s,n)=>{let r=a.allTools.filter(c=>Fw.has(c.name)),i=Fl(a.getParentMemory()),o=new at,l=Bw(a.workDir,i,s);if(m.info("SINGLE_EXPLORE",`${n} started`,{prompt:s.substring(0,80),toolCount:r.length}),a.abortSignal?.aborted)return {id:n,prompt:s,output:"",error:"aborted before start"};try{let c=`explore_${n}_${Date.now()}`,u=await a.orchestrator.runSession({sessionId:c,prompt:s,providerId:a.providerId,modelName:a.modelName,abortSignal:a.abortSignal,buildHostConfig:(d,p)=>({sessionId:c,configKey:`explore_${n}`,provider:d,llmConfig:p,workspacePath:a.workDir,workDir:a.workDir,instructions:l,systemPrompt:l,agentName:n,agentDescription:"Read-only codebase explorer",permissionManager:a.permissionManager,tools:r,memory:o,agentConfig:{temperature:.2,mode:"auto",maxIterations:30,maxRuntimeMs:300*1e3},sessionEnabled:!1,disableSystemPrompt:!0}),onRuntimeEvent:a.onSubAgentEvent?(d,p)=>a.onSubAgentEvent(n,{...d,workerRole:"Explore",workerTask:s.substring(0,60)},p):void 0});return m.info("SINGLE_EXPLORE",`${n} completed`,{output:(u.summary.output||"").substring(0,200)}),{id:n,prompt:s,output:u.summary.output||"(no output)"}}catch(c){return c.name==="AbortError"||a.abortSignal?.aborted?{id:n,prompt:s,output:"",error:"aborted"}:(m.error("SINGLE_EXPLORE",`${n} failed`,{error:c.message}),{id:n,prompt:s,output:"",error:c.message})}};return {name:"explore",description:`\u6D3E\u9063\u53EA\u8BFB\u5B50 agent \u63A2\u7D22\u4EE3\u7801\u5E93\u3002\u5B50 agent \u80FD\u770B\u5230\u5F53\u524D\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u3002
1911
1911
 
1912
1912
  \u652F\u6301\u5E76\u884C\uFF1A\u4F20\u5165 prompts \u6570\u7EC4\u540C\u65F6\u6D3E\u9063\u591A\u4E2A\u5B50 agent\uFF08\u6700\u591A ${jl} \u4E2A\uFF09\u3002
1913
1913
 
@@ -1924,7 +1924,7 @@ ${o.output}`);return i.join(`
1924
1924
 
1925
1925
  ---
1926
1926
 
1927
- `)}}}function jw(a,e,t){return `\u4F60\u662F\u4EE3\u7801\u63A2\u7D22\u4E13\u5BB6\uFF0C\u64C5\u957F\u5FEB\u901F\u7CBE\u51C6\u5B9A\u4F4D\u4EE3\u7801\u3002\u5DE5\u4F5C\u76EE\u5F55: ${a}
1927
+ `)}}}function Bw(a,e,t){return `\u4F60\u662F\u4EE3\u7801\u63A2\u7D22\u4E13\u5BB6\uFF0C\u64C5\u957F\u5FEB\u901F\u7CBE\u51C6\u5B9A\u4F4D\u4EE3\u7801\u3002\u5DE5\u4F5C\u76EE\u5F55: ${a}
1928
1928
  ${e?`
1929
1929
  ## \u5BF9\u8BDD\u80CC\u666F
1930
1930
  ${e}`:""}
@@ -1966,12 +1966,12 @@ ${u.map(d=>t.formatToolSchema(d)).join(`
1966
1966
 
1967
1967
  `)+`
1968
1968
 
1969
- \u7528 call_tool({ name, args }) \u8C03\u7528\u4E0A\u8FF0\u5DE5\u5177\u3002`}}}buildCallTool(){let e=this;return {name:"call_tool",description:"\u6267\u884C\u901A\u8FC7 select_tools \u67E5\u8BE2\u5230\u7684\u5DE5\u5177\u3002\u4F20\u5165\u5DE5\u5177\u540D\u548C\u53C2\u6570\u5373\u53EF\u3002",parameters:{type:"object",properties:{name:{type:"string",description:"\u8981\u8C03\u7528\u7684\u5DE5\u5177\u540D"},args:{type:"object",description:"\u5DE5\u5177\u53C2\u6570\uFF08\u6309 select_tools \u8FD4\u56DE\u7684\u53C2\u6570\u683C\u5F0F\uFF09",additionalProperties:true}},required:["name"]},async function(t,s){let{name:n,args:r={}}=t,i=e.toolMap.get(n);if(!i)return m.error("TOOL_TREE",`call_tool: unknown tool "${n}"`),`[ERROR] \u5DE5\u5177 "${n}" \u4E0D\u5B58\u5728\u3002\u8BF7\u5148\u7528 select_tools \u67E5\u8BE2\u53EF\u7528\u5DE5\u5177\u3002`;m.info("TOOL_TREE",`call_tool: ${n}`,{args:JSON.stringify(r).substring(0,200)});try{return await i.function(r,s)}catch(o){return m.error("TOOL_TREE",`call_tool: ${n} failed`,{error:o.message}),`[ERROR] ${n}: ${o.message}`}}}}getStatus(){return {total:this.toolMap.size,live:this.liveTools.length,categories:this.categories.length}}};W();var Uw=[".neox/project.md","NEOX.md"],cm=6e3;async function um(a){for(let e of Uw){let t=te__default.join(a,e);try{let s=await ce__default.readFile(t,"utf-8");if(!s.trim())continue;let n=s.length>cm?s.slice(0,cm)+`
1969
+ \u7528 call_tool({ name, args }) \u8C03\u7528\u4E0A\u8FF0\u5DE5\u5177\u3002`}}}buildCallTool(){let e=this;return {name:"call_tool",description:"\u6267\u884C\u901A\u8FC7 select_tools \u67E5\u8BE2\u5230\u7684\u5DE5\u5177\u3002\u4F20\u5165\u5DE5\u5177\u540D\u548C\u53C2\u6570\u5373\u53EF\u3002",parameters:{type:"object",properties:{name:{type:"string",description:"\u8981\u8C03\u7528\u7684\u5DE5\u5177\u540D"},args:{type:"object",description:"\u5DE5\u5177\u53C2\u6570\uFF08\u6309 select_tools \u8FD4\u56DE\u7684\u53C2\u6570\u683C\u5F0F\uFF09",additionalProperties:true}},required:["name"]},async function(t,s){let{name:n,args:r={}}=t,i=e.toolMap.get(n);if(!i)return m.error("TOOL_TREE",`call_tool: unknown tool "${n}"`),`[ERROR] \u5DE5\u5177 "${n}" \u4E0D\u5B58\u5728\u3002\u8BF7\u5148\u7528 select_tools \u67E5\u8BE2\u53EF\u7528\u5DE5\u5177\u3002`;m.info("TOOL_TREE",`call_tool: ${n}`,{args:JSON.stringify(r).substring(0,200)});try{return await i.function(r,s)}catch(o){return m.error("TOOL_TREE",`call_tool: ${n} failed`,{error:o.message}),`[ERROR] ${n}: ${o.message}`}}}}getStatus(){return {total:this.toolMap.size,live:this.liveTools.length,categories:this.categories.length}}};W();var Ww=[".neox/project.md","NEOX.md"],cm=6e3;async function um(a){for(let e of Ww){let t=te__default.join(a,e);try{let s=await ce__default.readFile(t,"utf-8");if(!s.trim())continue;let n=s.length>cm?s.slice(0,cm)+`
1970
1970
  ...(truncated)`:s;return m.info("PROJECT_MEMORY",`Loaded from ${e}`,{chars:s.length}),`
1971
1971
  ## \u9879\u76EE\u8BB0\u5FC6 (${e})
1972
- ${n}`}catch{}}return null}var Ww=new Set(["ptc_execute","ask_user","askUserTool","use_skill"]);function vo(a){let e={};for(let t of a){if(Ww.has(t.name)||typeof t.function!="function")continue;let s=t.permission?.category==="READ"||["readfile","search","search_files","list_directory","show_tree","smart_tree","analyze_code","git_status","git_diff","git_blame","git_branch_list","git_log","smart_read","get_definitions","get_references","search_symbol"].includes(t.name);e[t.name]={name:t.name,isReadOnly:s,fn:async n=>{let r=await t.function(n);return typeof r=="string"?r:JSON.stringify(r)}};}return e}function Ul(a){let e=vo(a),t=[];for(let[s,n]of Object.entries(e)){let r=a.find(d=>d.name===s);if(!r)continue;let i=r.parameters?.properties?Object.keys(r.parameters.properties):[],o=r.parameters?.required||[],l=i.map(d=>o.includes(d)?d:`${d}?`).join(", "),c=n.isReadOnly?"[R]":"[W]",u=(r.description||"").split(`
1972
+ ${n}`}catch{}}return null}var qw=new Set(["ptc_execute","ask_user","askUserTool","use_skill"]);function vo(a){let e={};for(let t of a){if(qw.has(t.name)||typeof t.function!="function")continue;let s=t.permission?.category==="READ"||["readfile","search","search_files","list_directory","show_tree","smart_tree","analyze_code","git_status","git_diff","git_blame","git_branch_list","git_log","smart_read","get_definitions","get_references","search_symbol"].includes(t.name);e[t.name]={name:t.name,isReadOnly:s,fn:async n=>{let r=await t.function(n);return typeof r=="string"?r:JSON.stringify(r)}};}return e}function Ul(a){let e=vo(a),t=[];for(let[s,n]of Object.entries(e)){let r=a.find(d=>d.name===s);if(!r)continue;let i=r.parameters?.properties?Object.keys(r.parameters.properties):[],o=r.parameters?.required||[],l=i.map(d=>o.includes(d)?d:`${d}?`).join(", "),c=n.isReadOnly?"[R]":"[W]",u=(r.description||"").split(`
1973
1973
  `)[0].substring(0,60);t.push(` ${c} await ${s}({ ${l} }) \u2014 ${u}`);}return t.join(`
1974
- `)}var qw=6e4,zw=15e3;async function Wl(a,e,t={}){let s=t.timeout??qw,n=t.maxOutputChars??zw,r=Date.now(),i=[],o=0,l=[],c=0,u={console:{log:(...h)=>{let g=h.map(f=>typeof f=="string"?f:JSON.stringify(f,null,2)).join(" ");c+=g.length,c<=n&&i.push(g);},error:(...h)=>{let g="[ERROR] "+h.map(String).join(" ");i.push(g);},warn:(...h)=>{let g="[WARN] "+h.map(String).join(" ");i.push(g);}},Promise,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,JSON,Array,Object,Map,Set,RegExp,Date,Math,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent};for(let[h,g]of Object.entries(e))u[h]=async f=>{if(t.signal?.aborted)throw new Error("Script aborted");o++;let b=Date.now(),y=await g.fn(f);return l.push({name:h,durationMs:Date.now()-b}),y};let d=dm.createContext(u),p=`(async () => {
1974
+ `)}var zw=6e4,Hw=15e3;async function Wl(a,e,t={}){let s=t.timeout??zw,n=t.maxOutputChars??Hw,r=Date.now(),i=[],o=0,l=[],c=0,u={console:{log:(...h)=>{let g=h.map(f=>typeof f=="string"?f:JSON.stringify(f,null,2)).join(" ");c+=g.length,c<=n&&i.push(g);},error:(...h)=>{let g="[ERROR] "+h.map(String).join(" ");i.push(g);},warn:(...h)=>{let g="[WARN] "+h.map(String).join(" ");i.push(g);}},Promise,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,JSON,Array,Object,Map,Set,RegExp,Date,Math,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent};for(let[h,g]of Object.entries(e))u[h]=async f=>{if(t.signal?.aborted)throw new Error("Script aborted");o++;let b=Date.now(),y=await g.fn(f);return l.push({name:h,durationMs:Date.now()-b}),y};let d=dm.createContext(u),p=`(async () => {
1975
1975
  ${a}
1976
1976
  })()`;try{let g=await new dm.Script(p,{filename:"ptc_script.js"}).runInNewContext(d,{timeout:s}),f=i.join(`
1977
1977
  `);if(g!=null){let b=typeof g=="string"?g:JSON.stringify(g,null,2);f?f+=`
@@ -2002,16 +2002,16 @@ ${c?c+`
2002
2002
  ${i.output}`}let o=i.toolCalls.map(c=>` ${c.name} (${c.durationMs}ms)`).join(`
2003
2003
  `);return `${`[PTC: ${i.toolCallCount} tool calls, ${i.durationMs}ms]`}
2004
2004
  ${o}
2005
- ${i.output}`}}}var wn=class{config;hostService;orchestrator;abortController=null;toolTreeEngine=null;constructor(e){this.config=e,this.hostService=new Nt({platformServices:e.services}),this.orchestrator=new $t({hostService:this.hostService,resolveProvider:e.resolveProvider}),m.info("SINGLE_AGENT","SingleAgentRuntime initialized");}async chat(e,t){let{sessionId:s,prompt:n,metadata:r}=e,i=e.providerId||this.config.providerId,o=e.modelName||this.config.modelName;m.info("SINGLE_AGENT","Chat started",{sessionId:s,promptLength:n.length});try{this.abortController=new AbortController;let l=Bl({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=pm(this.config.tools);c.push(b),m.info("SINGLE_AGENT","PTC tool injected");}this.toolTreeEngine=new bo(c);let u=this.toolTreeEngine.liveTools,p=[this.config.systemPrompt??"Single agent mode",Gl,Hw];if(this.config.enablePTC&&p.push(Jw),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 um(this.config.workDir);b&&p.push(b);}catch(b){m.warn("SINGLE_AGENT","Project memory load failed",{error:b.message});}let h=p.join(`
2005
+ ${i.output}`}}}var wn=class{config;hostService;orchestrator;abortController=null;toolTreeEngine=null;constructor(e){this.config=e,this.hostService=new Nt({platformServices:e.services}),this.orchestrator=new $t({hostService:this.hostService,resolveProvider:e.resolveProvider}),m.info("SINGLE_AGENT","SingleAgentRuntime initialized");}async chat(e,t){let{sessionId:s,prompt:n,metadata:r}=e,i=e.providerId||this.config.providerId,o=e.modelName||this.config.modelName;m.info("SINGLE_AGENT","Chat started",{sessionId:s,promptLength:n.length});try{this.abortController=new AbortController;let l=Bl({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=pm(this.config.tools);c.push(b),m.info("SINGLE_AGENT","PTC tool injected");}this.toolTreeEngine=new bo(c);let u=this.toolTreeEngine.liveTools,p=[this.config.systemPrompt??"Single agent mode",Gl,Jw];if(this.config.enablePTC&&p.push(Kw),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 um(this.config.workDir);b&&p.push(b);}catch(b){m.warn("SINGLE_AGENT","Project memory load failed",{error:b.message});}let h=p.join(`
2006
2006
 
2007
- `),g=await this.orchestrator.runSession({sessionId:s,prompt:n,metadata:r,providerId:i,modelName:o,buildHostConfig:(b,y)=>({sessionId:s,configKey:"single_agent",provider:b,llmConfig:y,workspacePath:this.config.workDir,workDir:this.config.workDir,instructions:h,systemPrompt:h,agentName:"SingleAgent",agentDescription:"Single agent mode runtime",permissionManager:this.config.permissionManager,tools:u,memory:this.config.memory,sessionEnabled:!0,enableFGTS:this.config.enableFGTS,agentConfig:{temperature:.3,mode:this.config.agentMode??"agent"}}),onRuntimeEvent:(b,y)=>{t?.onRuntimeEvent?.(b,y),this.handleRuntimeEvent(b,t);}}),f=g.summary.output||"Task completed";return t?.onComplete?.(f),m.info("SINGLE_AGENT","Chat completed",{sessionId:s,contextUsed:g.contextUsed}),f}catch(l){let c=l instanceof Error?l:new Error(String(l));throw t?.onError?.(c),m.error("SINGLE_AGENT","Chat failed",{error:c.message}),c}}handleRuntimeEvent(e,t){switch(e.type){case "text":t?.onText?.(e.text);break;case "thinking":t?.onThinking?.(e.text);break;case "tool_call":t?.onToolCall?.(e.name,e.args);break;case "tool_result":t?.onToolResult?.(e.name,e.result);break}}abort(){this.abortController?.abort(),this.abortController=null,this.hostService.clearAll(),m.info("SINGLE_AGENT","Aborted");}getModeName(){return "single"}},Hw=`
2007
+ `),g=await this.orchestrator.runSession({sessionId:s,prompt:n,metadata:r,providerId:i,modelName:o,buildHostConfig:(b,y)=>({sessionId:s,configKey:"single_agent",provider:b,llmConfig:y,workspacePath:this.config.workDir,workDir:this.config.workDir,instructions:h,systemPrompt:h,agentName:"SingleAgent",agentDescription:"Single agent mode runtime",permissionManager:this.config.permissionManager,tools:u,memory:this.config.memory,sessionEnabled:!0,enableFGTS:this.config.enableFGTS,agentConfig:{temperature:.3,mode:this.config.agentMode??"agent"}}),onRuntimeEvent:(b,y)=>{t?.onRuntimeEvent?.(b,y),this.handleRuntimeEvent(b,t);}}),f=g.summary.output||"Task completed";return t?.onComplete?.(f),m.info("SINGLE_AGENT","Chat completed",{sessionId:s,contextUsed:g.contextUsed}),f}catch(l){let c=l instanceof Error?l:new Error(String(l));throw t?.onError?.(c),m.error("SINGLE_AGENT","Chat failed",{error:c.message}),c}}handleRuntimeEvent(e,t){switch(e.type){case "text":t?.onText?.(e.text);break;case "thinking":t?.onThinking?.(e.text);break;case "tool_call":t?.onToolCall?.(e.name,e.args);break;case "tool_result":t?.onToolResult?.(e.name,e.result);break}}abort(){this.abortController?.abort(),this.abortController=null,this.hostService.clearAll(),m.info("SINGLE_AGENT","Aborted");}getModeName(){return "single"}},Jw=`
2008
2008
  ## \u5DE5\u5177\u6811
2009
2009
  \u4F60\u7684\u5DE5\u5177\u6309\u7C7B\u522B\u7EC4\u7EC7\u3002\u9ED8\u8BA4\u53EA\u6709\u5E38\u9A7B\u5DE5\u5177\u53EF\u7528\u3002
2010
2010
  \u9700\u8981\u5176\u4ED6\u5DE5\u5177\u65F6\uFF1A
2011
2011
  1. \u5148\u8C03\u7528 select_tools \u67E5\u8BE2\u7C7B\u522B\uFF0C\u83B7\u53D6\u5DE5\u5177\u7684\u5B8C\u6574\u63CF\u8FF0\u548C\u53C2\u6570\u683C\u5F0F
2012
2012
  2. \u518D\u8C03\u7528 call_tool({ name, args }) \u6267\u884C\u5177\u4F53\u5DE5\u5177
2013
2013
  \u4E0D\u8981\u731C\u6D4B\u5DE5\u5177\u540D\u548C\u53C2\u6570\uFF0C\u5FC5\u987B\u5148 select_tools \u83B7\u53D6 schema\u3002
2014
- `,Jw=`
2014
+ `,Kw=`
2015
2015
  ## Programmatic Tool Calling (PTC)
2016
2016
  \u4F60\u6709\u4E00\u4E2A\u7279\u6B8A\u5DE5\u5177 \`ptc_execute\`\uFF0C\u53EF\u4EE5\u5199 JavaScript \u811A\u672C\u4E00\u6B21\u6027\u7F16\u6392\u591A\u4E2A\u5DE5\u5177\u8C03\u7528\u3002
2017
2017
 
@@ -2054,12 +2054,12 @@ ${this.task.description}
2054
2054
 
2055
2055
  [\u4F9D\u8D56\u4EFB\u52A1\u7ED3\u679C]
2056
2056
  ${o}`};return this.spawnAndExecute(l,t)}catch(r){let i=r instanceof Error?r.message:String(r);return m.error("AGENT_POOL",`Task ${e.id} dependency wait failed`,{error:i}),{success:false,summary:"\u4F9D\u8D56\u7B49\u5F85\u5931\u8D25",error:i,duration:0}}}buildDependencyContext(e){let t=[];for(let[s,n]of e)n.success&&n.output&&t.push(`- ${s}: ${JSON.stringify(n.output).substring(0,200)}`);return t.join(`
2057
- `)}createAgentMemory(){return new at}clearAgentHost(e){let t=this.options.hostService;if(!t)return;t.getHost(e)?.dispose?.(),t.clearHost(e);}async spawn(e){let t=`agent-${++this.agentCounter}`,s=`${e.sessionId}_${t}`,n=e.taskId??`task-${Date.now()}-${this.agentCounter}`,r={id:n,description:e.prompt,priority:e.priority??1},i=oi(this.options.tools,t),o=this.createAgentMemory(),l=e.providerId??this.options.providerId,c=e.model??this.options.modelName,u=new Cn({id:t,index:this.agentCounter,task:r,sessionId:e.sessionId,workDir:this.options.workDir,eventBus:this.eventBus,orchestrator:this.options.orchestrator,resolveProvider:this.options.resolveProvider,providerId:l,modelName:c,permissionManager:this.options.permissionManager,tools:i,memory:o,onRuntimeEvent:this.options.onAgentRuntimeEvent?(f,b)=>this.options.onAgentRuntimeEvent(t,f,b):void 0});this.agents.set(t,u),m.info("AGENT_POOL",`Spawned agent ${t} (background)`,{prompt:e.prompt});let d=e.timeoutMs??5*6e4,p=null,h=false,g=()=>{p&&(clearTimeout(p),p=null),h||(h=true,this.agents.delete(t),this.clearAgentHost(s));};return p=setTimeout(()=>{h||(m.warn("AGENT_POOL",`Agent ${t} timed out after ${d/1e3}s, force aborting`),u.abort(),g(),this.sharedContext.storeTaskResult({taskId:r.id,agentId:t,success:false,error:`Worker timeout (${d/1e3}s)`,timestamp:Date.now()}),this.options.onAgentCompleted?.({agentId:t,success:false,error:`Worker timeout (${d/1e3}s)`}));},d),u.execute().then(f=>{h||(g(),this.sharedContext.storeTaskResult({taskId:r.id,agentId:t,success:f.success,output:f.output,error:f.error,timestamp:Date.now()}),m.info("AGENT_POOL",`Agent ${t} completed`,{success:f.success}),this.options.onAgentCompleted?.({agentId:t,success:f.success,output:f.output,error:f.error}));}).catch(f=>{h||(g(),this.sharedContext.storeTaskResult({taskId:r.id,agentId:t,success:false,error:f.message,timestamp:Date.now()}),m.error("AGENT_POOL",`Agent ${t} failed`,{error:f.message}),this.options.onAgentCompleted?.({agentId:t,success:false,error:f.message}));}),{agentId:t,taskId:n}}getActiveAgents(){return Array.from(this.agents.values()).map(e=>e.getInfo())}getActiveCount(){return this.agents.size}abortAll(){for(let e of this.agents.values())e.abort();this.agents.clear();}abort(e){let t=this.agents.get(e);return t?(t.abort(),this.agents.delete(e),true):false}reset(){this.abortAll(),this.agentCounter=0;}};W();W();var ql={openai:"https://api.openai.com/v1","openai-responses":"https://api.openai.com/v1",anthropic:"https://api.anthropic.com","anthropic-openai":"https://api.anthropic.com/v1",doubao:"https://ark.cn-beijing.volces.com/api/v3",gemini:"https://generativelanguage.googleapis.com",kimi:"https://api.moonshot.cn/v1"},rt=class{config;constructor(e){this.config=e??Oe(),this.config.providers||(this.config.providers={});}sanitizeId(e){return e.toLowerCase().trim().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").substring(0,48)}ensureValidId(e){let t=this.sanitizeId(e);if(!t)throw new Error("Provider ID must contain letters or numbers (allowed: lowercase letters, numbers, hyphen).");if(!/^[a-z0-9][a-z0-9-]*$/.test(t))throw new Error("Provider ID can only include lowercase letters, numbers, and hyphen.");return t}slugifyName(e){return this.sanitizeId(e)||"provider"}ensureProviderId(e,t){let s=e||this.slugifyName(t||"provider");if(this.config.providers||(this.config.providers={}),!this.config.providers[s])return s;let n=2,r=`${s}-${n}`;for(;this.config.providers[r];)n+=1,r=`${s}-${n}`;return r}persist(){ws(this.config);}getProviderCount(){return Object.keys(this.config.providers||{}).length}getProviders(){return Object.values(this.config.providers||{}).sort((e,t)=>e.name.localeCompare(t.name))}getProvider(e){if(e)return this.config.providers?.[e]}getDefaultProvider(){if(this.config.defaultProviderId){let t=this.getProvider(this.config.defaultProviderId);if(t)return t}let[e]=this.getProviders();return e&&(this.config.defaultProviderId=e.id,this.persist()),e}setDefaultProvider(e){let t=this.getProvider(e);if(!t)throw new Error(`Provider "${e}" does not exist.`);return this.config.defaultProviderId=e,this.persist(),t}addProvider(e){if(!e.name.trim())throw new Error("Provider name is required.");if(!e.apiKey.trim())throw new Error("Provider API key/token is required.");let t=this.ensureProviderId(e.id,e.name),s=new Date().toISOString(),n=e.baseUrl?.trim()||ql[e.protocol],r=(e.models||[]).map(o=>typeof o=="string"?{name:o,createdAt:s}:{...o,createdAt:o.createdAt||s}),i={id:t,name:e.name.trim(),protocol:e.protocol,apiKey:e.apiKey.trim(),baseUrl:n,urlSuffix:e.urlSuffix,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens,models:r,defaultModel:e.defaultModel||r[0]?.name,lastSelectedModel:e.defaultModel||r[0]?.name,createdAt:s,updatedAt:s};if(!i.defaultModel)throw new Error("At least one model is required when creating a provider.");return this.config.providers||(this.config.providers={}),this.config.providers[t]=i,(!this.config.defaultProviderId||e.setAsDefault)&&(this.config.defaultProviderId=t),this.persist(),i}updateProvider(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);let n=new Date().toISOString(),r={...s,...t,baseUrl:t.baseUrl?.trim()||s.baseUrl||ql[s.protocol],urlSuffix:t.urlSuffix!==void 0?t.urlSuffix:s.urlSuffix,apiKey:t.apiKey?.trim()||s.apiKey,maxTokens:t.maxTokens!==void 0?t.maxTokens:s.maxTokens,maxInputTokens:t.maxInputTokens!==void 0?t.maxInputTokens:s.maxInputTokens,updatedAt:n};if(t.protocol&&t.protocol!==s.protocol&&(r.protocol=t.protocol,t.baseUrl||(r.baseUrl=ql[t.protocol])),t.defaultModel){if(!r.models.some(o=>o.name===t.defaultModel))throw new Error(`Model "${t.defaultModel}" does not exist for provider "${e}".`);r.defaultModel=t.defaultModel,r.lastSelectedModel=t.defaultModel;}return this.config.providers[e]=r,this.persist(),r}renameProvider(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);let n=this.ensureValidId(t);if(n===e)return s;if(this.config.providers?.[n])throw new Error(`Provider ID "${n}" already exists.`);delete this.config.providers[e];let r=new Date().toISOString(),i={...s,id:n,updatedAt:r};return this.config.providers[n]=i,this.config.defaultProviderId===e&&(this.config.defaultProviderId=n),this.persist(),i}deleteProvider(e){if(!this.config.providers?.[e])throw new Error(`Provider "${e}" does not exist.`);delete this.config.providers[e],this.config.defaultProviderId===e&&(this.config.defaultProviderId=void 0),this.persist();}addModel(e,t,s=false,n){let r=this.getProvider(e);if(!r)throw new Error(`Provider "${e}" does not exist.`);let i=t.trim();if(!i)throw new Error("Model name cannot be empty.");if(r.models.some(l=>l.name===i))throw new Error(`Model "${i}" already exists for provider "${e}".`);let o={...r,models:[...r.models,{name:i,createdAt:new Date().toISOString(),...n}],updatedAt:new Date().toISOString()};return (!r.defaultModel||s)&&(o.defaultModel=i,o.lastSelectedModel=i),this.config.providers[e]=o,this.persist(),o}removeModel(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);if(s.models.length<=1)throw new Error("A provider must have at least one model.");let n=s.models.filter(i=>i.name!==t);if(n.length===s.models.length)throw new Error(`Model "${t}" does not exist for provider "${e}".`);let r={...s,models:n,updatedAt:new Date().toISOString()};return s.defaultModel===t&&(r.defaultModel=n[0].name),s.lastSelectedModel===t&&(r.lastSelectedModel=r.defaultModel),this.config.providers[e]=r,this.persist(),r}updateModelConfig(e,t,s){let n=this.getProvider(e);if(!n)throw new Error(`Provider "${e}" does not exist.`);let r=n.models.findIndex(l=>l.name===t);if(r===-1)throw new Error(`Model "${t}" does not exist for provider "${e}".`);let i=[...n.models];i[r]={...i[r],...s};let o={...n,models:i,updatedAt:new Date().toISOString()};return this.config.providers[e]=o,this.persist(),o}setLastSelectedModel(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);if(!s.models.some(r=>r.name===t))throw new Error(`Model "${t}" does not exist for provider "${e}".`);return s.lastSelectedModel=t,s.updatedAt=new Date().toISOString(),this.config.providers[e]=s,this.persist(),s}resolveModel(e,t){let s=this.getProvider(e);if(s)return t&&s.models.some(r=>r.name===t)?t:s.lastSelectedModel||s.defaultModel||s.models[0]?.name}};var zl={"claude-opus-4-5-20250514":["reasoning","creative","thorough","\u6DF1\u5EA6\u601D\u8003","\u590D\u6742\u63A8\u7406"],"claude-sonnet-4-5-20250514":["coding","fast","accurate","\u4EE3\u7801","\u5FEB\u901F"],"claude-haiku-4-5-20250514":["fast","cheap","simple","\u8F7B\u91CF","\u4F4E\u6210\u672C"],"claude-opus-4-20250514":["reasoning","creative","thorough","\u6DF1\u5EA6\u601D\u8003"],"claude-sonnet-4-20250514":["coding","fast","accurate","\u4EE3\u7801"],"gpt-5.2":["reasoning","coding","thorough","\u6DF1\u5EA6\u63A8\u7406","\u5168\u80FD"],"gpt-5.2-mini":["reasoning","fast","balanced","\u63A8\u7406","\u5FEB\u901F"],"gpt-5.2-codex":["coding","agent","autonomous","\u4EE3\u7801\u4E13\u5BB6","\u81EA\u4E3B\u7F16\u7A0B"],"gpt-5.2-codex-high":["coding","agent","thorough","\u4EE3\u7801","\u6DF1\u5EA6\u7F16\u7A0B","\u6700\u5F3A"],"gpt-5.2-codex-medium":["coding","agent","balanced","\u4EE3\u7801","\u6027\u4EF7\u6BD4"],"gpt-5.1":["reasoning","coding","balanced","\u903B\u8F91\u7F1C\u5BC6","\u901A\u7528"],"gpt-5.1-mini":["fast","cheap","coding","\u5FEB\u901F","\u4F4E\u6210\u672C"],"gpt-5.1-codex":["coding","agent","autonomous","\u4EE3\u7801","\u7F16\u7A0B"],"gpt-5.1-codex-max":["coding","agent","thorough","\u4EE3\u7801","\u6DF1\u5EA6\u7F16\u7A0B"],o3:["reasoning","math","science","\u6DF1\u5EA6\u63A8\u7406","\u6570\u5B66"],"o4-mini":["reasoning","fast","coding","\u63A8\u7406","\u5FEB\u901F"],"gemini-3-pro-preview":["ui","design","vision","creative","UI\u8BBE\u8BA1","\u754C\u9762","\u89C6\u89C9"],"gemini-3.0-pro":["ui","design","vision","creative","UI\u8BBE\u8BA1","\u754C\u9762"],"gemini-3.0-flash":["ui","fast","vision","UI","\u5FEB\u901F"],"gemini-2.5-pro":["reasoning","long-context","vision","\u63A8\u7406","\u957F\u4E0A\u4E0B\u6587"],"gemini-2.5-flash":["fast","vision","multimodal","\u5FEB\u901F","\u591A\u6A21\u6001"],"deepseek-v3":["coding","reasoning","cheap","\u4EE3\u7801","\u6027\u4EF7\u6BD4"],"deepseek-r1":["reasoning","math","thinking","\u6DF1\u5EA6\u63A8\u7406","\u6570\u5B66"],"qwen-max":["chinese","reasoning","coding","\u4E2D\u6587","\u63A8\u7406"],"qwen-turbo":["chinese","fast","cheap","\u4E2D\u6587","\u5FEB\u901F"]},mm=6,At=class{providerStore;scope;constructor(e,t="assistant"){this.providerStore=e??new rt,this.scope=t;}readLegacyScopedConfig(e){if(this.scope==="assistant"){let t=e.assistant;return {...t??{},workerPool:t?.workerPool??[]}}return {workerPool:[]}}readScopedRunModeConfig(e){return e.runConfig?.modes?.[this.scope]}getConfig(){let e=Oe(),t=this.readScopedRunModeConfig(e);return t?{mainAgent:t.mainAgent,workerPool:t.workerPool??[],maxConcurrent:t.maxConcurrent,ccbReviewMode:t.ccbReviewMode,createdAt:t.createdAt,updatedAt:t.updatedAt}:this.readLegacyScopedConfig(e)}saveConfig(e){let t=Oe(),s=new Date().toISOString(),n=t.runConfig?.modes?.[this.scope]??{},r={...n,mainAgent:e.mainAgent,workerPool:e.workerPool??[],maxConcurrent:e.maxConcurrent,ccbReviewMode:e.ccbReviewMode,updatedAt:s,createdAt:n.createdAt||s};t.runConfig={...t.runConfig??{},modes:{...t.runConfig?.modes??{},[this.scope]:r}},this.scope==="assistant"&&(t.assistant={...e,updatedAt:s,createdAt:t.assistant?.createdAt||s}),ws(t);}getNetworkRoles(){let e=Oe(),t=e.runConfig?.modes?.network?.networkRoles;if(Array.isArray(t))return t;let s=e.assistant?.networkRoles;return Array.isArray(s)?s:[]}setNetworkRoles(e){let t=Oe(),s=new Date().toISOString(),n=t.runConfig?.modes?.network??{};t.runConfig={...t.runConfig??{},modes:{...t.runConfig?.modes??{},network:{...n,networkRoles:e,updatedAt:s,createdAt:n.createdAt||s}}},ws(t);}getMainAgent(){let e=this.getConfig();if(e.mainAgent)return e.mainAgent;let t=this.providerStore.getDefaultProvider();if(t)return {providerId:t.id,model:t.lastSelectedModel||t.defaultModel||t.models[0]?.name}}setMainAgent(e){let t=this.getConfig();t.mainAgent=e,this.saveConfig(t);}getSupervisorAgent(){return this.getConfig().supervisorAgent}setSupervisorAgent(e){let t=this.getConfig();t.supervisorAgent=e,this.saveConfig(t);}getWorkerPool(){return this.getConfig().workerPool||[]}getMaxConcurrent(){let e=this.getConfig();return typeof e.maxConcurrent=="number"&&Number.isFinite(e.maxConcurrent)?e.maxConcurrent:void 0}setMaxConcurrent(e){let t=this.getConfig();typeof e=="number"&&Number.isFinite(e)&&e>0?t.maxConcurrent=Math.floor(e):delete t.maxConcurrent,this.saveConfig(t);}getCCBReviewMode(){let t=this.getConfig().ccbReviewMode;return t==="single"?"single-role":t==="multi"?"multi-model":t??"multi-role"}setCCBReviewMode(e){let t=this.getConfig();t.ccbReviewMode=e,this.saveConfig(t);}setWorkerPool(e){let t=this.getConfig();t.workerPool=e,this.saveConfig(t);}addWorkerModel(e,t,s=true){let n=this.getWorkerPool();if(n.some(o=>o.providerId===e&&o.model===t))return;let i=this.getModelTraits(t);n.push({providerId:e,model:t,enabled:s,traits:i}),this.setWorkerPool(n);}removeWorkerModel(e,t){let n=this.getWorkerPool().filter(r=>!(r.providerId===e&&r.model===t));this.setWorkerPool(n);}toggleWorkerModel(e,t){let s=this.getWorkerPool(),n=s.find(r=>r.providerId===e&&r.model===t);n&&(n.enabled=!n.enabled,this.setWorkerPool(s));}getEnabledWorkerModels(){return this.getWorkerPool().filter(e=>e.enabled)}getAvailableModels(){let e=this.providerStore.getProviders(),t=[];for(let s of e)for(let n of s.models){let r=this.getModelTraits(n.name);t.push({providerId:s.id,providerName:s.name,model:n.name,traits:r});}return t}selectWorkerByTraits(e){let t=this.getEnabledWorkerModels();if(t.length===0)return;let s=t.map(n=>{let r=n.traits||[],i=e.filter(o=>r.includes(o)).length;return {entry:n,score:i}});return s.sort((n,r)=>r.score-n.score),s[0]?.entry}getModelTraits(e){if(zl[e])return [...zl[e]];let t=e.toLowerCase();for(let[i,o]of Object.entries(zl))if(t.includes(i.toLowerCase())||i.toLowerCase().includes(t))return [...o];let s=Yi.getModel(e);if(!s)return [];let n=[],r=s.scores||{};return (r.coding??0)>=85&&n.push("coding"),(r.reasoning??0)>=85&&n.push("reasoning"),(r.vision??0)>=80&&n.push("vision"),(r.creativity??0)>=85&&n.push("creative"),(r.speed??0)>=85&&n.push("fast"),(r.cost??0)>=85&&n.push("low-cost"),s.supportsThinking&&n.push("thinking"),s.supportsVision&&n.push("multimodal"),s.maxInputTokens>=5e5&&n.push("long-context"),n}updateWorkerTraits(e,t,s){let n=this.getWorkerPool(),r=n.find(i=>i.providerId===e&&i.model===t);r&&(r.traits=s,this.setWorkerPool(n));}addWorkerTraits(e,t,s){let n=this.getWorkerPool(),r=n.find(i=>i.providerId===e&&i.model===t);if(r){let i=r.traits||[],o=[...new Set([...i,...s])];r.traits=o,this.setWorkerPool(n);}}initializeDefaults(){if(this.getConfig().workerPool.length>0)return;let t=this.providerStore.getDefaultProvider();if(!t)return;let s=t.models.map((n,r)=>({providerId:t.id,model:n.name,enabled:r===0,traits:this.getModelTraits(n.name)}));this.setWorkerPool(s);}};var Hl={coordinator:["reasoning","thorough","long-context"],scout:["fast","cheap","low-cost","vision"],worker:["coding","agent","balanced","fast"],compressor:["fast","cheap","reasoning"],verifier:["reasoning","coding","thorough"]};function it(a){return (a||"").trim().toLowerCase()}function Yw(a){let e=it(a);return e?/(探索|调研|收集|搜集|scan|explore|research|investigate|find)/i.test(e)?"scout":/(总结|摘要|归纳|压缩|提炼|summarize|compress|distill)/i.test(e)?"compressor":/(校验|验证|检查|核对|verify|validate|check|assert)/i.test(e)?"verifier":/(规划|统筹|拆分|协调|plan|coordinate|orchestrate)/i.test(e)?"coordinator":"worker":"worker"}function Xw(a){let e=it(a),t=new Set;return /(ui|前端|界面|视觉|image|vision|design)/i.test(e)&&(t.add("vision"),t.add("creative")),/(代码|实现|修复|重构|coding|implement|fix|refactor)/i.test(e)&&t.add("coding"),/(复杂|架构|推理|analysis|reason|complex)/i.test(e)&&(t.add("reasoning"),t.add("thorough")),/(快速|尽快|cheap|低成本|fast|quick)/i.test(e)&&(t.add("fast"),t.add("cheap")),Array.from(t)}function Qw(a){let e=it(a);return e.includes("claude")?"claude":e.includes("gpt")||e==="o3"||e.includes("o4")||e.includes("o1")?"gpt":e.includes("gemini")?"gemini":e.includes("deepseek")?"deepseek":e.includes("qwen")?"qwen":"other"}function Zw(a,e){let t=it(e),s=Qw(e);if(a==="scout"){if(t.includes("haiku")||t.includes("flash")||t.includes("mini"))return 2;if(s==="gemini")return 1.5;if(s==="claude"||s==="gpt")return 1}if(a==="worker"){if(t.includes("codex"))return 2;if(t.includes("sonnet")||t.includes("opus"))return 1.5;if(s==="deepseek")return 1}if(a==="compressor"){if(t.includes("mini")||t.includes("haiku")||t.includes("flash"))return 2;if(s==="gpt"||s==="claude")return 1}if(a==="verifier"){if(t.includes("opus")||t.includes("sonnet")||t.includes("gpt-5")||t.includes("gpt-4"))return 2;if(s==="claude"||s==="gpt")return 1}if(a==="coordinator"){if(t.includes("opus")||t.includes("gpt-5")||t.includes("sonnet"))return 2;if(s==="claude"||s==="gpt")return 1}return 0}var wo=class{options;constructor(e){this.options=e;}selectModel(e){let t=e.role??Yw(e.task),s=this.options.getEnabledWorkers();if(s.length===0)return {providerId:this.options.defaultProviderId,model:this.options.defaultModel,role:t,confidence:0,reason:"worker_pool_empty_fallback_default",requiredTraits:Hl[t]};if(e.explicitWorkerId){let u=this.findByWorkerIdOrModel(e.explicitWorkerId,s);if(u)return {providerId:u.providerId,model:u.model,role:t,confidence:1,reason:`explicit_worker_selected:${e.explicitWorkerId}`,requiredTraits:Hl[t]}}let n=new Set(Array.from(e.avoidModels||[]).map(it)),r=s.filter(u=>!n.has(it(u.model))),i=r.length>0?r:s,o=Array.from(new Set([...Hl[t],...Xw(e.task)])),l=i[0],c=Number.NEGATIVE_INFINITY;for(let u of i){let d=new Set((u.traits||[]).map(it)),p=o.reduce((f,b)=>d.has(it(b))?f+2:f,0),h=Zw(t,u.model),g=p+h;g>c&&(c=g,l=u);}return {providerId:l.providerId,model:l.model,role:t,confidence:Math.max(.1,Math.min(1,c/12)),reason:`policy_selected(role=${t},score=${c.toFixed(1)})`,requiredTraits:o}}findByWorkerIdOrModel(e,t){let s=it(e),n=t.find(i=>it(i.providerId)===s);if(n)return n;let r=t.find(i=>it(i.model)===s);return r||t.find(i=>it(i.providerId).includes(s)||it(i.model).includes(s))}};function Co(a){let e=it(a);if(e&&(e==="coordinator"||e==="scout"||e==="worker"||e==="compressor"||e==="verifier"))return e}var ko=null;function Kl(a){ko=a,m.debug("ASSISTANT_TOOLS","Context set",{sessionId:a.sessionId});}function So(){ko=null;}function Vl(){if(!ko)throw new Error("Assistant tools context not initialized");return ko}var Jl=null;function Yl(){return Jl||(Jl=new At(new rt)),Jl}function eC(){let e=Yl().getEnabledWorkerModels();return e.length===0?"\uFF08\u6682\u65E0\u53EF\u7528 Worker \u6A21\u578B\uFF09":`\u53EF\u7528 Worker \u6A21\u578B\uFF1A
2057
+ `)}createAgentMemory(){return new at}clearAgentHost(e){let t=this.options.hostService;if(!t)return;t.getHost(e)?.dispose?.(),t.clearHost(e);}async spawn(e){let t=`agent-${++this.agentCounter}`,s=`${e.sessionId}_${t}`,n=e.taskId??`task-${Date.now()}-${this.agentCounter}`,r={id:n,description:e.prompt,priority:e.priority??1},i=oi(this.options.tools,t),o=this.createAgentMemory(),l=e.providerId??this.options.providerId,c=e.model??this.options.modelName,u=new Cn({id:t,index:this.agentCounter,task:r,sessionId:e.sessionId,workDir:this.options.workDir,eventBus:this.eventBus,orchestrator:this.options.orchestrator,resolveProvider:this.options.resolveProvider,providerId:l,modelName:c,permissionManager:this.options.permissionManager,tools:i,memory:o,onRuntimeEvent:this.options.onAgentRuntimeEvent?(f,b)=>this.options.onAgentRuntimeEvent(t,f,b):void 0});this.agents.set(t,u),m.info("AGENT_POOL",`Spawned agent ${t} (background)`,{prompt:e.prompt});let d=e.timeoutMs??5*6e4,p=null,h=false,g=()=>{p&&(clearTimeout(p),p=null),h||(h=true,this.agents.delete(t),this.clearAgentHost(s));};return p=setTimeout(()=>{h||(m.warn("AGENT_POOL",`Agent ${t} timed out after ${d/1e3}s, force aborting`),u.abort(),g(),this.sharedContext.storeTaskResult({taskId:r.id,agentId:t,success:false,error:`Worker timeout (${d/1e3}s)`,timestamp:Date.now()}),this.options.onAgentCompleted?.({agentId:t,success:false,error:`Worker timeout (${d/1e3}s)`}));},d),u.execute().then(f=>{h||(g(),this.sharedContext.storeTaskResult({taskId:r.id,agentId:t,success:f.success,output:f.output,error:f.error,timestamp:Date.now()}),m.info("AGENT_POOL",`Agent ${t} completed`,{success:f.success}),this.options.onAgentCompleted?.({agentId:t,success:f.success,output:f.output,error:f.error}));}).catch(f=>{h||(g(),this.sharedContext.storeTaskResult({taskId:r.id,agentId:t,success:false,error:f.message,timestamp:Date.now()}),m.error("AGENT_POOL",`Agent ${t} failed`,{error:f.message}),this.options.onAgentCompleted?.({agentId:t,success:false,error:f.message}));}),{agentId:t,taskId:n}}getActiveAgents(){return Array.from(this.agents.values()).map(e=>e.getInfo())}getActiveCount(){return this.agents.size}abortAll(){for(let e of this.agents.values())e.abort();this.agents.clear();}abort(e){let t=this.agents.get(e);return t?(t.abort(),this.agents.delete(e),true):false}reset(){this.abortAll(),this.agentCounter=0;}};W();W();var ql={openai:"https://api.openai.com/v1","openai-responses":"https://api.openai.com/v1",anthropic:"https://api.anthropic.com","anthropic-openai":"https://api.anthropic.com/v1",doubao:"https://ark.cn-beijing.volces.com/api/v3",gemini:"https://generativelanguage.googleapis.com",kimi:"https://api.moonshot.cn/v1"},rt=class{config;constructor(e){this.config=e??Oe(),this.config.providers||(this.config.providers={});}sanitizeId(e){return e.toLowerCase().trim().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").substring(0,48)}ensureValidId(e){let t=this.sanitizeId(e);if(!t)throw new Error("Provider ID must contain letters or numbers (allowed: lowercase letters, numbers, hyphen).");if(!/^[a-z0-9][a-z0-9-]*$/.test(t))throw new Error("Provider ID can only include lowercase letters, numbers, and hyphen.");return t}slugifyName(e){return this.sanitizeId(e)||"provider"}ensureProviderId(e,t){let s=e||this.slugifyName(t||"provider");if(this.config.providers||(this.config.providers={}),!this.config.providers[s])return s;let n=2,r=`${s}-${n}`;for(;this.config.providers[r];)n+=1,r=`${s}-${n}`;return r}persist(){ws(this.config);}getProviderCount(){return Object.keys(this.config.providers||{}).length}getProviders(){return Object.values(this.config.providers||{}).sort((e,t)=>e.name.localeCompare(t.name))}getProvider(e){if(e)return this.config.providers?.[e]}getDefaultProvider(){if(this.config.defaultProviderId){let t=this.getProvider(this.config.defaultProviderId);if(t)return t}let[e]=this.getProviders();return e&&(this.config.defaultProviderId=e.id,this.persist()),e}setDefaultProvider(e){let t=this.getProvider(e);if(!t)throw new Error(`Provider "${e}" does not exist.`);return this.config.defaultProviderId=e,this.persist(),t}addProvider(e){if(!e.name.trim())throw new Error("Provider name is required.");if(!e.apiKey.trim())throw new Error("Provider API key/token is required.");let t=this.ensureProviderId(e.id,e.name),s=new Date().toISOString(),n=e.baseUrl?.trim()||ql[e.protocol],r=(e.models||[]).map(o=>typeof o=="string"?{name:o,createdAt:s}:{...o,createdAt:o.createdAt||s}),i={id:t,name:e.name.trim(),protocol:e.protocol,apiKey:e.apiKey.trim(),baseUrl:n,urlSuffix:e.urlSuffix,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens,models:r,defaultModel:e.defaultModel||r[0]?.name,lastSelectedModel:e.defaultModel||r[0]?.name,createdAt:s,updatedAt:s};if(!i.defaultModel)throw new Error("At least one model is required when creating a provider.");return this.config.providers||(this.config.providers={}),this.config.providers[t]=i,(!this.config.defaultProviderId||e.setAsDefault)&&(this.config.defaultProviderId=t),this.persist(),i}updateProvider(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);let n=new Date().toISOString(),r={...s,...t,baseUrl:t.baseUrl?.trim()||s.baseUrl||ql[s.protocol],urlSuffix:t.urlSuffix!==void 0?t.urlSuffix:s.urlSuffix,apiKey:t.apiKey?.trim()||s.apiKey,maxTokens:t.maxTokens!==void 0?t.maxTokens:s.maxTokens,maxInputTokens:t.maxInputTokens!==void 0?t.maxInputTokens:s.maxInputTokens,updatedAt:n};if(t.protocol&&t.protocol!==s.protocol&&(r.protocol=t.protocol,t.baseUrl||(r.baseUrl=ql[t.protocol])),t.defaultModel){if(!r.models.some(o=>o.name===t.defaultModel))throw new Error(`Model "${t.defaultModel}" does not exist for provider "${e}".`);r.defaultModel=t.defaultModel,r.lastSelectedModel=t.defaultModel;}return this.config.providers[e]=r,this.persist(),r}renameProvider(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);let n=this.ensureValidId(t);if(n===e)return s;if(this.config.providers?.[n])throw new Error(`Provider ID "${n}" already exists.`);delete this.config.providers[e];let r=new Date().toISOString(),i={...s,id:n,updatedAt:r};return this.config.providers[n]=i,this.config.defaultProviderId===e&&(this.config.defaultProviderId=n),this.persist(),i}deleteProvider(e){if(!this.config.providers?.[e])throw new Error(`Provider "${e}" does not exist.`);delete this.config.providers[e],this.config.defaultProviderId===e&&(this.config.defaultProviderId=void 0),this.persist();}addModel(e,t,s=false,n){let r=this.getProvider(e);if(!r)throw new Error(`Provider "${e}" does not exist.`);let i=t.trim();if(!i)throw new Error("Model name cannot be empty.");if(r.models.some(l=>l.name===i))throw new Error(`Model "${i}" already exists for provider "${e}".`);let o={...r,models:[...r.models,{name:i,createdAt:new Date().toISOString(),...n}],updatedAt:new Date().toISOString()};return (!r.defaultModel||s)&&(o.defaultModel=i,o.lastSelectedModel=i),this.config.providers[e]=o,this.persist(),o}removeModel(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);if(s.models.length<=1)throw new Error("A provider must have at least one model.");let n=s.models.filter(i=>i.name!==t);if(n.length===s.models.length)throw new Error(`Model "${t}" does not exist for provider "${e}".`);let r={...s,models:n,updatedAt:new Date().toISOString()};return s.defaultModel===t&&(r.defaultModel=n[0].name),s.lastSelectedModel===t&&(r.lastSelectedModel=r.defaultModel),this.config.providers[e]=r,this.persist(),r}updateModelConfig(e,t,s){let n=this.getProvider(e);if(!n)throw new Error(`Provider "${e}" does not exist.`);let r=n.models.findIndex(l=>l.name===t);if(r===-1)throw new Error(`Model "${t}" does not exist for provider "${e}".`);let i=[...n.models];i[r]={...i[r],...s};let o={...n,models:i,updatedAt:new Date().toISOString()};return this.config.providers[e]=o,this.persist(),o}setLastSelectedModel(e,t){let s=this.getProvider(e);if(!s)throw new Error(`Provider "${e}" does not exist.`);if(!s.models.some(r=>r.name===t))throw new Error(`Model "${t}" does not exist for provider "${e}".`);return s.lastSelectedModel=t,s.updatedAt=new Date().toISOString(),this.config.providers[e]=s,this.persist(),s}resolveModel(e,t){let s=this.getProvider(e);if(s)return t&&s.models.some(r=>r.name===t)?t:s.lastSelectedModel||s.defaultModel||s.models[0]?.name}};var zl={"claude-opus-4-5-20250514":["reasoning","creative","thorough","\u6DF1\u5EA6\u601D\u8003","\u590D\u6742\u63A8\u7406"],"claude-sonnet-4-5-20250514":["coding","fast","accurate","\u4EE3\u7801","\u5FEB\u901F"],"claude-haiku-4-5-20250514":["fast","cheap","simple","\u8F7B\u91CF","\u4F4E\u6210\u672C"],"claude-opus-4-20250514":["reasoning","creative","thorough","\u6DF1\u5EA6\u601D\u8003"],"claude-sonnet-4-20250514":["coding","fast","accurate","\u4EE3\u7801"],"gpt-5.2":["reasoning","coding","thorough","\u6DF1\u5EA6\u63A8\u7406","\u5168\u80FD"],"gpt-5.2-mini":["reasoning","fast","balanced","\u63A8\u7406","\u5FEB\u901F"],"gpt-5.2-codex":["coding","agent","autonomous","\u4EE3\u7801\u4E13\u5BB6","\u81EA\u4E3B\u7F16\u7A0B"],"gpt-5.2-codex-high":["coding","agent","thorough","\u4EE3\u7801","\u6DF1\u5EA6\u7F16\u7A0B","\u6700\u5F3A"],"gpt-5.2-codex-medium":["coding","agent","balanced","\u4EE3\u7801","\u6027\u4EF7\u6BD4"],"gpt-5.1":["reasoning","coding","balanced","\u903B\u8F91\u7F1C\u5BC6","\u901A\u7528"],"gpt-5.1-mini":["fast","cheap","coding","\u5FEB\u901F","\u4F4E\u6210\u672C"],"gpt-5.1-codex":["coding","agent","autonomous","\u4EE3\u7801","\u7F16\u7A0B"],"gpt-5.1-codex-max":["coding","agent","thorough","\u4EE3\u7801","\u6DF1\u5EA6\u7F16\u7A0B"],o3:["reasoning","math","science","\u6DF1\u5EA6\u63A8\u7406","\u6570\u5B66"],"o4-mini":["reasoning","fast","coding","\u63A8\u7406","\u5FEB\u901F"],"gemini-3-pro-preview":["ui","design","vision","creative","UI\u8BBE\u8BA1","\u754C\u9762","\u89C6\u89C9"],"gemini-3.0-pro":["ui","design","vision","creative","UI\u8BBE\u8BA1","\u754C\u9762"],"gemini-3.0-flash":["ui","fast","vision","UI","\u5FEB\u901F"],"gemini-2.5-pro":["reasoning","long-context","vision","\u63A8\u7406","\u957F\u4E0A\u4E0B\u6587"],"gemini-2.5-flash":["fast","vision","multimodal","\u5FEB\u901F","\u591A\u6A21\u6001"],"deepseek-v3":["coding","reasoning","cheap","\u4EE3\u7801","\u6027\u4EF7\u6BD4"],"deepseek-r1":["reasoning","math","thinking","\u6DF1\u5EA6\u63A8\u7406","\u6570\u5B66"],"qwen-max":["chinese","reasoning","coding","\u4E2D\u6587","\u63A8\u7406"],"qwen-turbo":["chinese","fast","cheap","\u4E2D\u6587","\u5FEB\u901F"]},mm=6,At=class{providerStore;scope;constructor(e,t="assistant"){this.providerStore=e??new rt,this.scope=t;}readLegacyScopedConfig(e){if(this.scope==="assistant"){let t=e.assistant;return {...t??{},workerPool:t?.workerPool??[]}}return {workerPool:[]}}readScopedRunModeConfig(e){return e.runConfig?.modes?.[this.scope]}getConfig(){let e=Oe(),t=this.readScopedRunModeConfig(e);return t?{mainAgent:t.mainAgent,workerPool:t.workerPool??[],maxConcurrent:t.maxConcurrent,ccbReviewMode:t.ccbReviewMode,createdAt:t.createdAt,updatedAt:t.updatedAt}:this.readLegacyScopedConfig(e)}saveConfig(e){let t=Oe(),s=new Date().toISOString(),n=t.runConfig?.modes?.[this.scope]??{},r={...n,mainAgent:e.mainAgent,workerPool:e.workerPool??[],maxConcurrent:e.maxConcurrent,ccbReviewMode:e.ccbReviewMode,updatedAt:s,createdAt:n.createdAt||s};t.runConfig={...t.runConfig??{},modes:{...t.runConfig?.modes??{},[this.scope]:r}},this.scope==="assistant"&&(t.assistant={...e,updatedAt:s,createdAt:t.assistant?.createdAt||s}),ws(t);}getNetworkRoles(){let e=Oe(),t=e.runConfig?.modes?.network?.networkRoles;if(Array.isArray(t))return t;let s=e.assistant?.networkRoles;return Array.isArray(s)?s:[]}setNetworkRoles(e){let t=Oe(),s=new Date().toISOString(),n=t.runConfig?.modes?.network??{};t.runConfig={...t.runConfig??{},modes:{...t.runConfig?.modes??{},network:{...n,networkRoles:e,updatedAt:s,createdAt:n.createdAt||s}}},ws(t);}getMainAgent(){let e=this.getConfig();if(e.mainAgent)return e.mainAgent;let t=this.providerStore.getDefaultProvider();if(t)return {providerId:t.id,model:t.lastSelectedModel||t.defaultModel||t.models[0]?.name}}setMainAgent(e){let t=this.getConfig();t.mainAgent=e,this.saveConfig(t);}getSupervisorAgent(){return this.getConfig().supervisorAgent}setSupervisorAgent(e){let t=this.getConfig();t.supervisorAgent=e,this.saveConfig(t);}getWorkerPool(){return this.getConfig().workerPool||[]}getMaxConcurrent(){let e=this.getConfig();return typeof e.maxConcurrent=="number"&&Number.isFinite(e.maxConcurrent)?e.maxConcurrent:void 0}setMaxConcurrent(e){let t=this.getConfig();typeof e=="number"&&Number.isFinite(e)&&e>0?t.maxConcurrent=Math.floor(e):delete t.maxConcurrent,this.saveConfig(t);}getCCBReviewMode(){let t=this.getConfig().ccbReviewMode;return t==="single"?"single-role":t==="multi"?"multi-model":t??"multi-role"}setCCBReviewMode(e){let t=this.getConfig();t.ccbReviewMode=e,this.saveConfig(t);}setWorkerPool(e){let t=this.getConfig();t.workerPool=e,this.saveConfig(t);}addWorkerModel(e,t,s=true){let n=this.getWorkerPool();if(n.some(o=>o.providerId===e&&o.model===t))return;let i=this.getModelTraits(t);n.push({providerId:e,model:t,enabled:s,traits:i}),this.setWorkerPool(n);}removeWorkerModel(e,t){let n=this.getWorkerPool().filter(r=>!(r.providerId===e&&r.model===t));this.setWorkerPool(n);}toggleWorkerModel(e,t){let s=this.getWorkerPool(),n=s.find(r=>r.providerId===e&&r.model===t);n&&(n.enabled=!n.enabled,this.setWorkerPool(s));}getEnabledWorkerModels(){return this.getWorkerPool().filter(e=>e.enabled)}getAvailableModels(){let e=this.providerStore.getProviders(),t=[];for(let s of e)for(let n of s.models){let r=this.getModelTraits(n.name);t.push({providerId:s.id,providerName:s.name,model:n.name,traits:r});}return t}selectWorkerByTraits(e){let t=this.getEnabledWorkerModels();if(t.length===0)return;let s=t.map(n=>{let r=n.traits||[],i=e.filter(o=>r.includes(o)).length;return {entry:n,score:i}});return s.sort((n,r)=>r.score-n.score),s[0]?.entry}getModelTraits(e){if(zl[e])return [...zl[e]];let t=e.toLowerCase();for(let[i,o]of Object.entries(zl))if(t.includes(i.toLowerCase())||i.toLowerCase().includes(t))return [...o];let s=Yi.getModel(e);if(!s)return [];let n=[],r=s.scores||{};return (r.coding??0)>=85&&n.push("coding"),(r.reasoning??0)>=85&&n.push("reasoning"),(r.vision??0)>=80&&n.push("vision"),(r.creativity??0)>=85&&n.push("creative"),(r.speed??0)>=85&&n.push("fast"),(r.cost??0)>=85&&n.push("low-cost"),s.supportsThinking&&n.push("thinking"),s.supportsVision&&n.push("multimodal"),s.maxInputTokens>=5e5&&n.push("long-context"),n}updateWorkerTraits(e,t,s){let n=this.getWorkerPool(),r=n.find(i=>i.providerId===e&&i.model===t);r&&(r.traits=s,this.setWorkerPool(n));}addWorkerTraits(e,t,s){let n=this.getWorkerPool(),r=n.find(i=>i.providerId===e&&i.model===t);if(r){let i=r.traits||[],o=[...new Set([...i,...s])];r.traits=o,this.setWorkerPool(n);}}initializeDefaults(){if(this.getConfig().workerPool.length>0)return;let t=this.providerStore.getDefaultProvider();if(!t)return;let s=t.models.map((n,r)=>({providerId:t.id,model:n.name,enabled:r===0,traits:this.getModelTraits(n.name)}));this.setWorkerPool(s);}};var Hl={coordinator:["reasoning","thorough","long-context"],scout:["fast","cheap","low-cost","vision"],worker:["coding","agent","balanced","fast"],compressor:["fast","cheap","reasoning"],verifier:["reasoning","coding","thorough"]};function it(a){return (a||"").trim().toLowerCase()}function Xw(a){let e=it(a);return e?/(探索|调研|收集|搜集|scan|explore|research|investigate|find)/i.test(e)?"scout":/(总结|摘要|归纳|压缩|提炼|summarize|compress|distill)/i.test(e)?"compressor":/(校验|验证|检查|核对|verify|validate|check|assert)/i.test(e)?"verifier":/(规划|统筹|拆分|协调|plan|coordinate|orchestrate)/i.test(e)?"coordinator":"worker":"worker"}function Qw(a){let e=it(a),t=new Set;return /(ui|前端|界面|视觉|image|vision|design)/i.test(e)&&(t.add("vision"),t.add("creative")),/(代码|实现|修复|重构|coding|implement|fix|refactor)/i.test(e)&&t.add("coding"),/(复杂|架构|推理|analysis|reason|complex)/i.test(e)&&(t.add("reasoning"),t.add("thorough")),/(快速|尽快|cheap|低成本|fast|quick)/i.test(e)&&(t.add("fast"),t.add("cheap")),Array.from(t)}function Zw(a){let e=it(a);return e.includes("claude")?"claude":e.includes("gpt")||e==="o3"||e.includes("o4")||e.includes("o1")?"gpt":e.includes("gemini")?"gemini":e.includes("deepseek")?"deepseek":e.includes("qwen")?"qwen":"other"}function eC(a,e){let t=it(e),s=Zw(e);if(a==="scout"){if(t.includes("haiku")||t.includes("flash")||t.includes("mini"))return 2;if(s==="gemini")return 1.5;if(s==="claude"||s==="gpt")return 1}if(a==="worker"){if(t.includes("codex"))return 2;if(t.includes("sonnet")||t.includes("opus"))return 1.5;if(s==="deepseek")return 1}if(a==="compressor"){if(t.includes("mini")||t.includes("haiku")||t.includes("flash"))return 2;if(s==="gpt"||s==="claude")return 1}if(a==="verifier"){if(t.includes("opus")||t.includes("sonnet")||t.includes("gpt-5")||t.includes("gpt-4"))return 2;if(s==="claude"||s==="gpt")return 1}if(a==="coordinator"){if(t.includes("opus")||t.includes("gpt-5")||t.includes("sonnet"))return 2;if(s==="claude"||s==="gpt")return 1}return 0}var wo=class{options;constructor(e){this.options=e;}selectModel(e){let t=e.role??Xw(e.task),s=this.options.getEnabledWorkers();if(s.length===0)return {providerId:this.options.defaultProviderId,model:this.options.defaultModel,role:t,confidence:0,reason:"worker_pool_empty_fallback_default",requiredTraits:Hl[t]};if(e.explicitWorkerId){let u=this.findByWorkerIdOrModel(e.explicitWorkerId,s);if(u)return {providerId:u.providerId,model:u.model,role:t,confidence:1,reason:`explicit_worker_selected:${e.explicitWorkerId}`,requiredTraits:Hl[t]}}let n=new Set(Array.from(e.avoidModels||[]).map(it)),r=s.filter(u=>!n.has(it(u.model))),i=r.length>0?r:s,o=Array.from(new Set([...Hl[t],...Qw(e.task)])),l=i[0],c=Number.NEGATIVE_INFINITY;for(let u of i){let d=new Set((u.traits||[]).map(it)),p=o.reduce((f,b)=>d.has(it(b))?f+2:f,0),h=eC(t,u.model),g=p+h;g>c&&(c=g,l=u);}return {providerId:l.providerId,model:l.model,role:t,confidence:Math.max(.1,Math.min(1,c/12)),reason:`policy_selected(role=${t},score=${c.toFixed(1)})`,requiredTraits:o}}findByWorkerIdOrModel(e,t){let s=it(e),n=t.find(i=>it(i.providerId)===s);if(n)return n;let r=t.find(i=>it(i.model)===s);return r||t.find(i=>it(i.providerId).includes(s)||it(i.model).includes(s))}};function Co(a){let e=it(a);if(e&&(e==="coordinator"||e==="scout"||e==="worker"||e==="compressor"||e==="verifier"))return e}var ko=null;function Kl(a){ko=a,m.debug("ASSISTANT_TOOLS","Context set",{sessionId:a.sessionId});}function So(){ko=null;}function Vl(){if(!ko)throw new Error("Assistant tools context not initialized");return ko}var Jl=null;function Yl(){return Jl||(Jl=new At(new rt)),Jl}function tC(){let e=Yl().getEnabledWorkerModels();return e.length===0?"\uFF08\u6682\u65E0\u53EF\u7528 Worker \u6A21\u578B\uFF09":`\u53EF\u7528 Worker \u6A21\u578B\uFF1A
2058
2058
  ${e.map((s,n)=>{let r=s.traits?.join(", ")||"\u901A\u7528";return ` ${n+1}. [${s.providerId}] ${s.model} - \u7279\u6027: ${r}`}).join(`
2059
- `)}`}function tC(a){let t=Yl().getEnabledWorkerModels(),s=t.find(r=>r.providerId===a);if(s||(s=t.find(r=>r.model===a),s))return s;let n=a.toLowerCase();return s=t.find(r=>r.model.toLowerCase().includes(n)||r.providerId.toLowerCase().includes(n)),s}function sC(a){let{task:e,workerId:t,role:s,context:n}=a,r=Co(s);if(n.selectWorkerModel){let o=n.selectWorkerModel({task:e,role:r,workerId:t});if(o.model)return {model:o.model,providerId:o.providerId,role:o.role??r,reason:o.reason}}if(t){let o=tC(t);if(o)return {model:o.model,providerId:o.providerId,role:r,reason:"manual_worker_id"}}let i=Yl().getEnabledWorkerModels();if(i.length>0){let o=i[0];return {model:o.model,providerId:o.providerId,role:r,reason:"fallback_first_enabled_worker"}}return {role:r,reason:"no_worker_available"}}async function nC(a,e,t){let s=Date.now(),n=500;for(;Date.now()-s<t;)if(await new Promise(i=>setTimeout(i,n)),(a.getActiveWorkerCount?.()??0)<e)return true;return false}function rC(){return {name:"spawn_agent",description:`\u521B\u5EFA\u5F02\u6B65\u540E\u53F0\u5B50 agent \u6267\u884C\u4EFB\u52A1\u3002\u5B50 agent \u72EC\u7ACB\u8FD0\u884C\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u6C47\u62A5\u7ED3\u679C\u3002
2059
+ `)}`}function sC(a){let t=Yl().getEnabledWorkerModels(),s=t.find(r=>r.providerId===a);if(s||(s=t.find(r=>r.model===a),s))return s;let n=a.toLowerCase();return s=t.find(r=>r.model.toLowerCase().includes(n)||r.providerId.toLowerCase().includes(n)),s}function nC(a){let{task:e,workerId:t,role:s,context:n}=a,r=Co(s);if(n.selectWorkerModel){let o=n.selectWorkerModel({task:e,role:r,workerId:t});if(o.model)return {model:o.model,providerId:o.providerId,role:o.role??r,reason:o.reason}}if(t){let o=sC(t);if(o)return {model:o.model,providerId:o.providerId,role:r,reason:"manual_worker_id"}}let i=Yl().getEnabledWorkerModels();if(i.length>0){let o=i[0];return {model:o.model,providerId:o.providerId,role:r,reason:"fallback_first_enabled_worker"}}return {role:r,reason:"no_worker_available"}}async function rC(a,e,t){let s=Date.now(),n=500;for(;Date.now()-s<t;)if(await new Promise(i=>setTimeout(i,n)),(a.getActiveWorkerCount?.()??0)<e)return true;return false}function iC(){return {name:"spawn_agent",description:`\u521B\u5EFA\u5F02\u6B65\u540E\u53F0\u5B50 agent \u6267\u884C\u4EFB\u52A1\u3002\u5B50 agent \u72EC\u7ACB\u8FD0\u884C\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u6C47\u62A5\u7ED3\u679C\u3002
2060
2060
  \u9002\u7528\u4E8E\u8017\u65F6\u8F83\u957F\u3001\u4E0D\u9700\u8981\u7ACB\u5373\u83B7\u53D6\u7ED3\u679C\u7684\u4EFB\u52A1\u3002
2061
2061
 
2062
- ${eC()}`,parameters:{type:"object",properties:{task:{type:"string",description:"\u4EFB\u52A1\u63CF\u8FF0"},workerId:{type:"string",description:"Worker \u7684 providerId \u6216 model \u540D\u79F0"},role:{type:"string",enum:["scout","worker","compressor","verifier","coordinator"],description:"\u4EFB\u52A1\u89D2\u8272"}},required:["task"]},async function(e){let t=Vl(),{task:s,workerId:n,role:r}=e,i=typeof t.maxConcurrent=="number"?t.maxConcurrent:8,o=3e4,l=t.getActiveWorkerCount?.()??0;if(l>=i&&(m.info("ASSISTANT_SPAWN",`Workers full (${l}/${i}), queuing...`),!await nC(t,i,o)))return JSON.stringify({error:`All workers busy for ${o/1e3}s, try again later`});let c=sC({task:s,workerId:n,role:r,context:t});m.info("ASSISTANT_SPAWN","spawn_agent",{task:s.substring(0,80),model:c.model,role:c.role});try{let u=await t.agentPool.spawn({prompt:s,sessionId:t.sessionId,model:c.model,providerId:c.providerId});return JSON.stringify({agentId:u.agentId,status:"spawned",model:c.model,role:c.role,note:"Agent is running in background. Results will be announced automatically on completion."})}catch(u){return JSON.stringify({error:u.message})}}}}function iC(){return {name:"query_agent",description:"\u67E5\u8BE2\u540E\u53F0\u5B50 agent \u7684\u8FD0\u884C\u72B6\u6001",parameters:{type:"object",properties:{agentId:{type:"string",description:"Agent ID"}},required:["agentId"]},async function(a){let e=Vl();try{let s=e.agentPool.getActiveAgents().find(n=>n.id===a.agentId);return JSON.stringify(s?{id:s.id,status:s.status,progress:s.progress,currentTask:s.currentTask}:{error:"Agent not found",agentId:a.agentId})}catch(t){return JSON.stringify({error:t.message})}}}}function oC(){return {name:"terminate_agent",description:"\u7EC8\u6B62\u6307\u5B9A\u7684\u540E\u53F0\u5B50 agent",parameters:{type:"object",properties:{agentId:{type:"string",description:"Agent ID"},reason:{type:"string",description:"\u7EC8\u6B62\u539F\u56E0"}},required:["agentId"]},async function(a){let e=Vl(),{agentId:t,reason:s="User requested"}=a;try{let n=e.agentPool.abort(t);return n&&m.info("ASSISTANT_TOOLS",`Terminated ${t}`,{reason:s}),JSON.stringify({success:n,agentId:t,reason:s})}catch(n){return JSON.stringify({error:n.message})}}}}function Xl(){return [rC(),iC(),oC()]}W();W();var gm={high:0,normal:1,low:2},xo=class extends EventEmitter{items=[];cap;constructor(e=50){super(),this.cap=e;}genId(){return randomBytes(8).toString("hex")}enqueue(e){let t=this.genId(),s={...e,id:t,enqueuedAt:Date.now()};if(this.items.length>=this.cap){let n=this.items.findIndex(r=>r.priority==="low");if(n>=0)this.items.splice(n,1)[0].metadata?.reject?.(new Error("Queue overflow, message dropped"));else {let r=this.items.findIndex(i=>i.priority==="normal");r>=0&&this.items.splice(r,1)[0].metadata?.reject?.(new Error("Queue overflow, message dropped"));}}return this.items.push(s),this.emit("enqueued",s),t}drain(){if(this.items.length===0)return [];let e=this.items.splice(0);return e.sort((t,s)=>{let n=gm[t.priority]-gm[s.priority];return n!==0?n:t.enqueuedAt-s.enqueuedAt}),e}peek(){return this.items[0]}size(){return this.items.length}isEmpty(){return this.items.length===0}clear(){for(let e of this.items)e.metadata?.reject?.(new Error("Queue cleared"));this.items=[];}waitForMessage(e){return this.items.length>0?Promise.resolve():new Promise((t,s)=>{let n=()=>{i(),t();},r=()=>{i(),s(new Error("Aborted"));},i=()=>{this.removeListener("enqueued",n),e?.removeEventListener("abort",r);};this.once("enqueued",n),e?.addEventListener("abort",r,{once:true});})}};W();var To=class a extends EventEmitter{sessionId;config;queue;status="idle";running=false;abortController=null;memory;mainAgentId="main";pendingAnnounces=[];announceDebounceTimer=null;announceDebounceBuffer=[];consecutiveAnnounceTurns=0;recentTurnTimestamps=[];static LOOP_WINDOW_MS=8e3;static LOOP_MAX_TURNS=4;constructor(e){super(),this.sessionId=e.sessionId,this.config=e,this.queue=new xo,this.memory=new at;}getStatus(){return this.status}injectMessage(e,t){return new Promise((s,n)=>{this.queue.enqueue({type:"user_message",content:e,source:t??{channel:"cli"},priority:"normal",metadata:{resolve:s,reject:n}});})}injectAnnounce(e){this.status==="thinking"||this.status==="tool_executing"?(this.pendingAnnounces.push(e),m.info("SESSION",`Announce queued (agent busy): ${e.agentId}`)):(this.announceDebounceBuffer.push(e),m.info("SESSION",`Announce buffered (debounce): ${e.agentId}`),this.announceDebounceTimer&&clearTimeout(this.announceDebounceTimer),this.announceDebounceTimer=setTimeout(()=>{this.flushAnnounceBuffer();},200));}flushAnnounceBuffer(){if(this.announceDebounceTimer=null,this.announceDebounceBuffer.length===0)return;let e=this.announceDebounceBuffer.splice(0),t=e.map(s=>{let n=s.status==="ok"?"\u2705":s.status==="error"?"\u274C":"\u23F1\uFE0F",r=s.status==="ok"?"\u5B8C\u6210":s.status==="error"?"\u5931\u8D25":"\u8D85\u65F6";return `${n} \u5B50 Agent ${s.agentId} ${r}:
2062
+ ${tC()}`,parameters:{type:"object",properties:{task:{type:"string",description:"\u4EFB\u52A1\u63CF\u8FF0"},workerId:{type:"string",description:"Worker \u7684 providerId \u6216 model \u540D\u79F0"},role:{type:"string",enum:["scout","worker","compressor","verifier","coordinator"],description:"\u4EFB\u52A1\u89D2\u8272"}},required:["task"]},async function(e){let t=Vl(),{task:s,workerId:n,role:r}=e,i=typeof t.maxConcurrent=="number"?t.maxConcurrent:8,o=3e4,l=t.getActiveWorkerCount?.()??0;if(l>=i&&(m.info("ASSISTANT_SPAWN",`Workers full (${l}/${i}), queuing...`),!await rC(t,i,o)))return JSON.stringify({error:`All workers busy for ${o/1e3}s, try again later`});let c=nC({task:s,workerId:n,role:r,context:t});m.info("ASSISTANT_SPAWN","spawn_agent",{task:s.substring(0,80),model:c.model,role:c.role});try{let u=await t.agentPool.spawn({prompt:s,sessionId:t.sessionId,model:c.model,providerId:c.providerId});return JSON.stringify({agentId:u.agentId,status:"spawned",model:c.model,role:c.role,note:"Agent is running in background. Results will be announced automatically on completion."})}catch(u){return JSON.stringify({error:u.message})}}}}function oC(){return {name:"query_agent",description:"\u67E5\u8BE2\u540E\u53F0\u5B50 agent \u7684\u8FD0\u884C\u72B6\u6001",parameters:{type:"object",properties:{agentId:{type:"string",description:"Agent ID"}},required:["agentId"]},async function(a){let e=Vl();try{let s=e.agentPool.getActiveAgents().find(n=>n.id===a.agentId);return JSON.stringify(s?{id:s.id,status:s.status,progress:s.progress,currentTask:s.currentTask}:{error:"Agent not found",agentId:a.agentId})}catch(t){return JSON.stringify({error:t.message})}}}}function aC(){return {name:"terminate_agent",description:"\u7EC8\u6B62\u6307\u5B9A\u7684\u540E\u53F0\u5B50 agent",parameters:{type:"object",properties:{agentId:{type:"string",description:"Agent ID"},reason:{type:"string",description:"\u7EC8\u6B62\u539F\u56E0"}},required:["agentId"]},async function(a){let e=Vl(),{agentId:t,reason:s="User requested"}=a;try{let n=e.agentPool.abort(t);return n&&m.info("ASSISTANT_TOOLS",`Terminated ${t}`,{reason:s}),JSON.stringify({success:n,agentId:t,reason:s})}catch(n){return JSON.stringify({error:n.message})}}}}function Xl(){return [iC(),oC(),aC()]}W();W();var gm={high:0,normal:1,low:2},xo=class extends EventEmitter{items=[];cap;constructor(e=50){super(),this.cap=e;}genId(){return randomBytes(8).toString("hex")}enqueue(e){let t=this.genId(),s={...e,id:t,enqueuedAt:Date.now()};if(this.items.length>=this.cap){let n=this.items.findIndex(r=>r.priority==="low");if(n>=0)this.items.splice(n,1)[0].metadata?.reject?.(new Error("Queue overflow, message dropped"));else {let r=this.items.findIndex(i=>i.priority==="normal");r>=0&&this.items.splice(r,1)[0].metadata?.reject?.(new Error("Queue overflow, message dropped"));}}return this.items.push(s),this.emit("enqueued",s),t}drain(){if(this.items.length===0)return [];let e=this.items.splice(0);return e.sort((t,s)=>{let n=gm[t.priority]-gm[s.priority];return n!==0?n:t.enqueuedAt-s.enqueuedAt}),e}peek(){return this.items[0]}size(){return this.items.length}isEmpty(){return this.items.length===0}clear(){for(let e of this.items)e.metadata?.reject?.(new Error("Queue cleared"));this.items=[];}waitForMessage(e){return this.items.length>0?Promise.resolve():new Promise((t,s)=>{let n=()=>{i(),t();},r=()=>{i(),s(new Error("Aborted"));},i=()=>{this.removeListener("enqueued",n),e?.removeEventListener("abort",r);};this.once("enqueued",n),e?.addEventListener("abort",r,{once:true});})}};W();var To=class a extends EventEmitter{sessionId;config;queue;status="idle";running=false;abortController=null;memory;mainAgentId="main";pendingAnnounces=[];announceDebounceTimer=null;announceDebounceBuffer=[];consecutiveAnnounceTurns=0;recentTurnTimestamps=[];static LOOP_WINDOW_MS=8e3;static LOOP_MAX_TURNS=4;constructor(e){super(),this.sessionId=e.sessionId,this.config=e,this.queue=new xo,this.memory=new at;}getStatus(){return this.status}injectMessage(e,t){return new Promise((s,n)=>{this.queue.enqueue({type:"user_message",content:e,source:t??{channel:"cli"},priority:"normal",metadata:{resolve:s,reject:n}});})}injectAnnounce(e){this.status==="thinking"||this.status==="tool_executing"?(this.pendingAnnounces.push(e),m.info("SESSION",`Announce queued (agent busy): ${e.agentId}`)):(this.announceDebounceBuffer.push(e),m.info("SESSION",`Announce buffered (debounce): ${e.agentId}`),this.announceDebounceTimer&&clearTimeout(this.announceDebounceTimer),this.announceDebounceTimer=setTimeout(()=>{this.flushAnnounceBuffer();},200));}flushAnnounceBuffer(){if(this.announceDebounceTimer=null,this.announceDebounceBuffer.length===0)return;let e=this.announceDebounceBuffer.splice(0),t=e.map(s=>{let n=s.status==="ok"?"\u2705":s.status==="error"?"\u274C":"\u23F1\uFE0F",r=s.status==="ok"?"\u5B8C\u6210":s.status==="error"?"\u5931\u8D25":"\u8D85\u65F6";return `${n} \u5B50 Agent ${s.agentId} ${r}:
2063
2063
  ${s.output}`});this.queue.enqueue({type:"announce",content:t.join(`
2064
2064
 
2065
2065
  ---
@@ -2076,7 +2076,7 @@ ${d}`);}catch{}let o=n?`
2076
2076
 
2077
2077
  ---
2078
2078
 
2079
- `)}async drainPendingAnnounces(){if(this.pendingAnnounces.length===0)return;let e=this.pendingAnnounces.splice(0);this.announceDebounceBuffer.push(...e),this.flushAnnounceBuffer();}setupContext(){Kl({agentPool:this.config.agentPool,sessionId:this.sessionId,agentId:this.mainAgentId,selectWorkerModel:this.config.selectWorkerModel,maxConcurrent:this.config.maxConcurrent,getActiveWorkerCount:()=>this.config.agentPool.getActiveCount(),getParentMemory:()=>this.memory,actionLog:this.config.actionLog});}setStatus(e){let t=this.status;this.status=e,t!==e&&this.emit("status_change",{from:t,to:e});}};function dC(){let e=new At(new rt).getEnabledWorkerModels(),t="";return e.length>0?t=e.map(s=>{let n=s.traits?.length?s.traits.join(", "):"\u901A\u7528";return ` - ${s.model}: [${n}]`}).join(`
2079
+ `)}async drainPendingAnnounces(){if(this.pendingAnnounces.length===0)return;let e=this.pendingAnnounces.splice(0);this.announceDebounceBuffer.push(...e),this.flushAnnounceBuffer();}setupContext(){Kl({agentPool:this.config.agentPool,sessionId:this.sessionId,agentId:this.mainAgentId,selectWorkerModel:this.config.selectWorkerModel,maxConcurrent:this.config.maxConcurrent,getActiveWorkerCount:()=>this.config.agentPool.getActiveCount(),getParentMemory:()=>this.memory,actionLog:this.config.actionLog});}setStatus(e){let t=this.status;this.status=e,t!==e&&this.emit("status_change",{from:t,to:e});}};function pC(){let e=new At(new rt).getEnabledWorkerModels(),t="";return e.length>0?t=e.map(s=>{let n=s.traits?.length?s.traits.join(", "):"\u901A\u7528";return ` - ${s.model}: [${n}]`}).join(`
2080
2080
  `):t=" (\u5C06\u4F7F\u7528\u9ED8\u8BA4\u6A21\u578B)",`
2081
2081
  ## \u4F60\u662F\u8C01
2082
2082
 
@@ -2109,7 +2109,7 @@ ${t}
2109
2109
  2. \u9700\u8981\u52A8\u624B\u5C31 spawn\uFF0C\u4E0D\u8981\u81EA\u5DF1\u7528\u5DE5\u5177
2110
2110
  3. \u72EC\u7ACB\u4EFB\u52A1\u540C\u65F6 spawn \u591A\u4E2A
2111
2111
  4. \u7B80\u6D01\uFF0C\u7B80\u6D01\uFF0C\u7B80\u6D01
2112
- `}function pC(){return {emit:()=>{},subscribe:()=>()=>{},on:()=>()=>{},getHistory:()=>[]}}var xn=class extends EventEmitter{config;hostService;orchestrator;agentPool;runConfigStore;mainAgentId="main";workerCounter=0;activeDelegateWorkers=new Set;modelPolicyRouter;modelFailureStreak=new Map;lastScoutSuccessAt=0;abortController=null;assistantMainMemory=null;session=null;sessionStarted=false;constructor(e){super(),this.config=e,this.runConfigStore=new At(new rt),this.modelPolicyRouter=new wo({getEnabledWorkers:()=>this.runConfigStore.getEnabledWorkerModels(),defaultProviderId:this.config.providerId,defaultModel:this.config.modelName}),this.hostService=new Nt({platformServices:e.services}),this.orchestrator=new $t({hostService:this.hostService,resolveProvider:e.resolveProvider});let t=pC();this.agentPool=new Ls({eventBus:t,orchestrator:this.orchestrator,resolveProvider:this.config.resolveProvider,providerId:this.config.providerId,modelName:this.config.modelName,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,sharedContext:void 0,hostService:this.hostService,onAgentRuntimeEvent:(s,n,r)=>{this.emit("worker_event",{agentId:s,event:n,tracker:r});},onAgentCompleted:s=>{this.handleSpawnAnnounce(s);}}),m.info("ASSISTANT_RUNTIME","AssistantRuntime initialized (Jarvis mode)");}ensureSession(e){return this.session?this.session:(this.session=new To({sessionId:e,orchestrator:this.orchestrator,hostService:this.hostService,agentPool:this.agentPool,services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt||"",buildAssistantInstructions:()=>dC(),buildWorkerInstructions:(t,s,n)=>this.buildWorkerInstructions(t,s,n),selectWorkerModel:t=>this.selectWorkerModelByPolicy(t),maxConcurrent:this.getMaxConcurrentWorkers(),actionLog:this.config.actionLog}),this.session.on("runtime_event",t=>{this.emit("worker_event",t);}),this.session.on("worker_start",t=>this.emit("worker_start",t)),this.session.on("turn_start",t=>{this.emit("worker_start",{agentId:"Main",task:t.prompt,model:this.config.modelName});}),this.session.on("turn_complete",t=>{this.emit("worker_complete",{agentId:"Main",success:true,summary:t.output});}),this.session.on("status_change",t=>{this.emit("session_status",t);}),this.sessionStarted||(this.sessionStarted=true,this.session.start().catch(t=>{m.error("ASSISTANT_RUNTIME",`Session loop crashed: ${t.message}`);})),this.session)}async chat(e){let{sessionId:t,prompt:s}=e,n=this.ensureSession(t);this.emit("worker_start",{agentId:"Main",task:s.substring(0,100),model:this.config.modelName});try{return await n.injectMessage(s,{channel:"cli"})}catch(r){throw this.emit("worker_complete",{agentId:"Main",success:false,error:r.message}),r}}injectMessage(e,t,s){this.ensureSession(e).injectMessage(t,s).catch(r=>{m.error("ASSISTANT_RUNTIME",`Inject message failed: ${r.message}`);});}getSessionStatus(){return this.session?.getStatus()??"idle"}isBusy(){let e=this.getSessionStatus();return e==="thinking"||e==="tool_executing"}abort(){this.session&&(this.session.abort(),this.session=null,this.sessionStarted=false),this.agentPool.abortAll(),this.hostService.clearAll(),Ct(),m.info("ASSISTANT_RUNTIME","Aborted");}getModeName(){return "assistant"}handleSpawnAnnounce(e){if(!this.session)return;let t=e.output||e.error||"(no output)";if(t.length<=500){this.emit("worker_result",{agentId:e.agentId,success:e.success,output:t,direct:true}),m.info("ANNOUNCE",`Direct SSE push for ${e.agentId} (${t.length} chars)`);return}let n={agentId:e.agentId,status:e.success?"ok":"error",output:t,summaryLine:e.success?"Task completed":`Error: ${e.error}`};this.session.injectAnnounce(n),m.info("ANNOUNCE",`Routed announce from ${e.agentId} \u2192 session`,{status:n.status});}selectWorkerModelByPolicy(e){let t=Co(e.role)??"worker";if(e.explicitModel)return {providerId:e.explicitProviderId??this.resolveProviderForModel(e.explicitModel)??this.config.providerId,model:e.explicitModel,role:t,reason:"explicit_model_requested"};let s=new Set(Array.from(this.modelFailureStreak.entries()).filter(([,r])=>r>=2).map(([r])=>r.toLowerCase())),n=this.modelPolicyRouter.selectModel({task:e.task,role:t,explicitWorkerId:e.workerId,avoidModels:s});return {providerId:n.providerId??this.config.providerId,model:n.model??this.config.modelName,role:n.role,reason:n.reason}}buildWorkerInstructions(e,t,s){let n="";s&&(n=`
2112
+ `}function mC(){return {emit:()=>{},subscribe:()=>()=>{},on:()=>()=>{},getHistory:()=>[]}}var xn=class extends EventEmitter{config;hostService;orchestrator;agentPool;runConfigStore;mainAgentId="main";workerCounter=0;activeDelegateWorkers=new Set;modelPolicyRouter;modelFailureStreak=new Map;lastScoutSuccessAt=0;abortController=null;assistantMainMemory=null;session=null;sessionStarted=false;constructor(e){super(),this.config=e,this.runConfigStore=new At(new rt),this.modelPolicyRouter=new wo({getEnabledWorkers:()=>this.runConfigStore.getEnabledWorkerModels(),defaultProviderId:this.config.providerId,defaultModel:this.config.modelName}),this.hostService=new Nt({platformServices:e.services}),this.orchestrator=new $t({hostService:this.hostService,resolveProvider:e.resolveProvider});let t=mC();this.agentPool=new Ls({eventBus:t,orchestrator:this.orchestrator,resolveProvider:this.config.resolveProvider,providerId:this.config.providerId,modelName:this.config.modelName,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,sharedContext:void 0,hostService:this.hostService,onAgentRuntimeEvent:(s,n,r)=>{this.emit("worker_event",{agentId:s,event:n,tracker:r});},onAgentCompleted:s=>{this.handleSpawnAnnounce(s);}}),m.info("ASSISTANT_RUNTIME","AssistantRuntime initialized (Jarvis mode)");}ensureSession(e){return this.session?this.session:(this.session=new To({sessionId:e,orchestrator:this.orchestrator,hostService:this.hostService,agentPool:this.agentPool,services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt||"",buildAssistantInstructions:()=>pC(),buildWorkerInstructions:(t,s,n)=>this.buildWorkerInstructions(t,s,n),selectWorkerModel:t=>this.selectWorkerModelByPolicy(t),maxConcurrent:this.getMaxConcurrentWorkers(),actionLog:this.config.actionLog}),this.session.on("runtime_event",t=>{this.emit("worker_event",t);}),this.session.on("worker_start",t=>this.emit("worker_start",t)),this.session.on("turn_start",t=>{this.emit("worker_start",{agentId:"Main",task:t.prompt,model:this.config.modelName});}),this.session.on("turn_complete",t=>{this.emit("worker_complete",{agentId:"Main",success:true,summary:t.output});}),this.session.on("status_change",t=>{this.emit("session_status",t);}),this.sessionStarted||(this.sessionStarted=true,this.session.start().catch(t=>{m.error("ASSISTANT_RUNTIME",`Session loop crashed: ${t.message}`);})),this.session)}async chat(e){let{sessionId:t,prompt:s}=e,n=this.ensureSession(t);this.emit("worker_start",{agentId:"Main",task:s.substring(0,100),model:this.config.modelName});try{return await n.injectMessage(s,{channel:"cli"})}catch(r){throw this.emit("worker_complete",{agentId:"Main",success:false,error:r.message}),r}}injectMessage(e,t,s){this.ensureSession(e).injectMessage(t,s).catch(r=>{m.error("ASSISTANT_RUNTIME",`Inject message failed: ${r.message}`);});}getSessionStatus(){return this.session?.getStatus()??"idle"}isBusy(){let e=this.getSessionStatus();return e==="thinking"||e==="tool_executing"}abort(){this.session&&(this.session.abort(),this.session=null,this.sessionStarted=false),this.agentPool.abortAll(),this.hostService.clearAll(),Ct(),m.info("ASSISTANT_RUNTIME","Aborted");}getModeName(){return "assistant"}handleSpawnAnnounce(e){if(!this.session)return;let t=e.output||e.error||"(no output)";if(t.length<=500){this.emit("worker_result",{agentId:e.agentId,success:e.success,output:t,direct:true}),m.info("ANNOUNCE",`Direct SSE push for ${e.agentId} (${t.length} chars)`);return}let n={agentId:e.agentId,status:e.success?"ok":"error",output:t,summaryLine:e.success?"Task completed":`Error: ${e.error}`};this.session.injectAnnounce(n),m.info("ANNOUNCE",`Routed announce from ${e.agentId} \u2192 session`,{status:n.status});}selectWorkerModelByPolicy(e){let t=Co(e.role)??"worker";if(e.explicitModel)return {providerId:e.explicitProviderId??this.resolveProviderForModel(e.explicitModel)??this.config.providerId,model:e.explicitModel,role:t,reason:"explicit_model_requested"};let s=new Set(Array.from(this.modelFailureStreak.entries()).filter(([,r])=>r>=2).map(([r])=>r.toLowerCase())),n=this.modelPolicyRouter.selectModel({task:e.task,role:t,explicitWorkerId:e.workerId,avoidModels:s});return {providerId:n.providerId??this.config.providerId,model:n.model??this.config.modelName,role:n.role,reason:n.reason}}buildWorkerInstructions(e,t,s){let n="";s&&(n=`
2113
2113
 
2114
2114
  ## \u5BF9\u8BDD\u80CC\u666F
2115
2115
  ${s}`);let r=`\u4F60\u662F\u4E00\u4E2A\u81EA\u4E3B\u6267\u884C\u4EFB\u52A1\u7684 Agent\u3002\u4F60\u7684\u5DE5\u4F5C\u76EE\u5F55\u662F: ${this.config.workDir}
@@ -2204,7 +2204,7 @@ ${e.codebaseInfo}`),e?.sessionSummary&&(t+=`
2204
2204
  ## \u4F1A\u8BDD\u4E0A\u4E0B\u6587
2205
2205
  ${e.sessionSummary}`),t+=`
2206
2206
 
2207
- \u8BF7\u5206\u6790\u8FD9\u4E2A\u8BF7\u6C42\uFF0C\u8F93\u51FA JSON \u683C\u5F0F\u7684\u5206\u6790\u7ED3\u679C\u3002`,t}var hm=["delete","remove","drop","\u5220\u9664","\u79FB\u9664","\u6E05\u9664","refactor","rewrite","restructure","\u91CD\u6784","\u91CD\u5199","core","kernel","engine","\u6838\u5FC3","\u5F15\u64CE","database","migration","schema","\u6570\u636E\u5E93","\u8FC1\u79FB","auth","security","credential","\u8BA4\u8BC1","\u5B89\u5168","\u5BC6\u94A5"];function ec(a,e){let t=e??hm,s=a.toLowerCase();return t.some(n=>s.includes(n.toLowerCase()))}W();var mC={enableCCB:true,enableClarification:true,riskKeywords:void 0},_o=class{llmCall;config;constructor(e){this.llmCall=e.llmCall,this.config={...mC,...e.config};}async analyze(e,t){m.info("TASK_ANALYZER","Starting task analysis",{requestLength:e.length});let s=Ql,n=Zl(e,{codebaseInfo:t?.codebaseInfo?`\u8BED\u8A00: ${t.codebaseInfo.language}, \u6846\u67B6: ${t.codebaseInfo.framework||"\u65E0"}`:void 0,sessionSummary:t?.sessionSummary});m.debug("TASK_ANALYZER","Calling LLM for analysis",{systemPromptLength:s.length,userPromptLength:n.length});try{let r=await this.llmCall(s,n);if(m.debug("TASK_ANALYZER","LLM call completed",{responseLength:r?.length||0,responsePreview:r?.substring(0,200)||"(empty)"}),!r||r.trim()==="")return m.warn("TASK_ANALYZER","LLM returned empty response, using default result"),this.getDefaultResult();let i=this.parseResponse(r);return this.postProcess(i,e)}catch(r){return m.error("TASK_ANALYZER","LLM call failed",{error:r?.message,stack:r?.stack}),this.getDefaultResult()}}parseResponse(e){try{if(m.debug("TASK_ANALYZER","Raw LLM response",{responseLength:e?.length||0,responsePreview:e?.substring(0,200)||"(empty)"}),!e||e.trim()==="")throw m.warn("TASK_ANALYZER","Empty LLM response received"),new Error("Empty response from LLM");let t=null,s=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(s&&(t=s[1].trim()),!t){let r=e.match(/\{[\s\S]*\}/);r&&(t=r[0]);}if(!t)throw m.warn("TASK_ANALYZER","No JSON found in response",{response:e.substring(0,500)}),new Error("No JSON found in response");let n=JSON.parse(t);if(!n.intent||!n.complexity||!n.routing)throw m.warn("TASK_ANALYZER","Missing required fields in parsed JSON",{parsed:n}),new Error("Missing required fields");return m.info("TASK_ANALYZER","Successfully parsed analysis result",{intent:n.intent.summary,complexity:n.complexity.score,path:n.routing.path}),n}catch(t){return m.error("TASK_ANALYZER","Failed to parse LLM response",{error:t?.message,responsePreview:e?.substring(0,300)||"(empty)"}),this.getDefaultResult()}}postProcess(e,t){let s={...e};return this.config.enableCCB&&ec(t,this.config.riskKeywords)&&s.routing.path==="simple"&&(s.routing.path="standard",s.routing.needsCCB=true,s.routing.reason+=" (\u5305\u542B\u98CE\u9669\u5173\u952E\u8BCD\uFF0C\u5347\u7EA7\u5230\u6807\u51C6\u8DEF\u5F84)"),this.config.enableCCB||(s.routing.needsCCB=false),this.config.enableClarification||(s.routing.needsClarification=false,s.routing.clarificationQuestions=void 0),s.routing.path!=="simple"&&this.config.enableCCB&&(s.routing.needsCCB=true),s}getDefaultResult(){return {intent:{summary:"\u65E0\u6CD5\u89E3\u6790\u7528\u6237\u610F\u56FE",domain:["unknown"],actionType:"other"},complexity:{score:3,reason:"LLM \u89E3\u6790\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BC4\u5206",dimensions:{scopeSize:3,technicalDepth:3,interdependency:3,ambiguity:5}},routing:{path:"simple",needsCCB:false,needsClarification:false,reason:"LLM \u89E3\u6790\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8DEF\u5F84"}}}quickRouteCheck(e){let t=e.trim();return /^(你好|hi|hello|hey|嗨|哈喽)[!!。.]*$/i.test(t)||/^(什么是|是什么|how to|what is|explain|解释一下|告诉我)[^,,。.!!??]*[??]?$/i.test(t)?"simple":null}updateConfig(e){this.config={...this.config,...e};}getConfig(){return {...this.config}}};function tc(a){return new _o(a)}var gC={autoConfirmCCB:false,complexityConfirmThreshold:7},Ro=class{config;constructor(e){this.config={...gC,...e};}handle(e){let{routing:t,complexity:s}=e;return t.needsClarification&&t.clarificationQuestions?.length?{path:t.path,needsUserConfirmation:true,confirmationMessage:this.buildClarificationMessage(t),clarificationQuestions:t.clarificationQuestions,metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}:s.score>=(this.config.complexityConfirmThreshold??7)&&!this.config.autoConfirmCCB?{path:t.path,needsUserConfirmation:true,confirmationMessage:this.buildComplexTaskMessage(e),metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}:t.needsCCB&&!this.config.autoConfirmCCB?{path:t.path,needsUserConfirmation:true,confirmationMessage:this.buildCCBConfirmMessage(e),metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}:{path:t.path,needsUserConfirmation:false,metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}}buildClarificationMessage(e){return `\u9700\u8981\u4E00\u4E9B\u6F84\u6E05\u624D\u80FD\u66F4\u597D\u5730\u5B8C\u6210\u4EFB\u52A1\uFF1A
2207
+ \u8BF7\u5206\u6790\u8FD9\u4E2A\u8BF7\u6C42\uFF0C\u8F93\u51FA JSON \u683C\u5F0F\u7684\u5206\u6790\u7ED3\u679C\u3002`,t}var hm=["delete","remove","drop","\u5220\u9664","\u79FB\u9664","\u6E05\u9664","refactor","rewrite","restructure","\u91CD\u6784","\u91CD\u5199","core","kernel","engine","\u6838\u5FC3","\u5F15\u64CE","database","migration","schema","\u6570\u636E\u5E93","\u8FC1\u79FB","auth","security","credential","\u8BA4\u8BC1","\u5B89\u5168","\u5BC6\u94A5"];function ec(a,e){let t=e??hm,s=a.toLowerCase();return t.some(n=>s.includes(n.toLowerCase()))}W();var gC={enableCCB:true,enableClarification:true,riskKeywords:void 0},_o=class{llmCall;config;constructor(e){this.llmCall=e.llmCall,this.config={...gC,...e.config};}async analyze(e,t){m.info("TASK_ANALYZER","Starting task analysis",{requestLength:e.length});let s=Ql,n=Zl(e,{codebaseInfo:t?.codebaseInfo?`\u8BED\u8A00: ${t.codebaseInfo.language}, \u6846\u67B6: ${t.codebaseInfo.framework||"\u65E0"}`:void 0,sessionSummary:t?.sessionSummary});m.debug("TASK_ANALYZER","Calling LLM for analysis",{systemPromptLength:s.length,userPromptLength:n.length});try{let r=await this.llmCall(s,n);if(m.debug("TASK_ANALYZER","LLM call completed",{responseLength:r?.length||0,responsePreview:r?.substring(0,200)||"(empty)"}),!r||r.trim()==="")return m.warn("TASK_ANALYZER","LLM returned empty response, using default result"),this.getDefaultResult();let i=this.parseResponse(r);return this.postProcess(i,e)}catch(r){return m.error("TASK_ANALYZER","LLM call failed",{error:r?.message,stack:r?.stack}),this.getDefaultResult()}}parseResponse(e){try{if(m.debug("TASK_ANALYZER","Raw LLM response",{responseLength:e?.length||0,responsePreview:e?.substring(0,200)||"(empty)"}),!e||e.trim()==="")throw m.warn("TASK_ANALYZER","Empty LLM response received"),new Error("Empty response from LLM");let t=null,s=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(s&&(t=s[1].trim()),!t){let r=e.match(/\{[\s\S]*\}/);r&&(t=r[0]);}if(!t)throw m.warn("TASK_ANALYZER","No JSON found in response",{response:e.substring(0,500)}),new Error("No JSON found in response");let n=JSON.parse(t);if(!n.intent||!n.complexity||!n.routing)throw m.warn("TASK_ANALYZER","Missing required fields in parsed JSON",{parsed:n}),new Error("Missing required fields");return m.info("TASK_ANALYZER","Successfully parsed analysis result",{intent:n.intent.summary,complexity:n.complexity.score,path:n.routing.path}),n}catch(t){return m.error("TASK_ANALYZER","Failed to parse LLM response",{error:t?.message,responsePreview:e?.substring(0,300)||"(empty)"}),this.getDefaultResult()}}postProcess(e,t){let s={...e};return this.config.enableCCB&&ec(t,this.config.riskKeywords)&&s.routing.path==="simple"&&(s.routing.path="standard",s.routing.needsCCB=true,s.routing.reason+=" (\u5305\u542B\u98CE\u9669\u5173\u952E\u8BCD\uFF0C\u5347\u7EA7\u5230\u6807\u51C6\u8DEF\u5F84)"),this.config.enableCCB||(s.routing.needsCCB=false),this.config.enableClarification||(s.routing.needsClarification=false,s.routing.clarificationQuestions=void 0),s.routing.path!=="simple"&&this.config.enableCCB&&(s.routing.needsCCB=true),s}getDefaultResult(){return {intent:{summary:"\u65E0\u6CD5\u89E3\u6790\u7528\u6237\u610F\u56FE",domain:["unknown"],actionType:"other"},complexity:{score:3,reason:"LLM \u89E3\u6790\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BC4\u5206",dimensions:{scopeSize:3,technicalDepth:3,interdependency:3,ambiguity:5}},routing:{path:"simple",needsCCB:false,needsClarification:false,reason:"LLM \u89E3\u6790\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8DEF\u5F84"}}}quickRouteCheck(e){let t=e.trim();return /^(你好|hi|hello|hey|嗨|哈喽)[!!。.]*$/i.test(t)||/^(什么是|是什么|how to|what is|explain|解释一下|告诉我)[^,,。.!!??]*[??]?$/i.test(t)?"simple":null}updateConfig(e){this.config={...this.config,...e};}getConfig(){return {...this.config}}};function tc(a){return new _o(a)}var hC={autoConfirmCCB:false,complexityConfirmThreshold:7},Ro=class{config;constructor(e){this.config={...hC,...e};}handle(e){let{routing:t,complexity:s}=e;return t.needsClarification&&t.clarificationQuestions?.length?{path:t.path,needsUserConfirmation:true,confirmationMessage:this.buildClarificationMessage(t),clarificationQuestions:t.clarificationQuestions,metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}:s.score>=(this.config.complexityConfirmThreshold??7)&&!this.config.autoConfirmCCB?{path:t.path,needsUserConfirmation:true,confirmationMessage:this.buildComplexTaskMessage(e),metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}:t.needsCCB&&!this.config.autoConfirmCCB?{path:t.path,needsUserConfirmation:true,confirmationMessage:this.buildCCBConfirmMessage(e),metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}:{path:t.path,needsUserConfirmation:false,metadata:{complexity:s.score,needsCCB:t.needsCCB,reason:t.reason}}}buildClarificationMessage(e){return `\u9700\u8981\u4E00\u4E9B\u6F84\u6E05\u624D\u80FD\u66F4\u597D\u5730\u5B8C\u6210\u4EFB\u52A1\uFF1A
2208
2208
  ${(e.clarificationQuestions??[]).map((s,n)=>`${n+1}. ${s}`).join(`
2209
2209
  `)}`}buildComplexTaskMessage(e){let{complexity:t,routing:s,intent:n}=e;return `## \u4EFB\u52A1\u5206\u6790\u7ED3\u679C
2210
2210
 
@@ -2434,9 +2434,9 @@ ${a.sessionSummary}
2434
2434
  3. \u4F7F\u7528 \`search\` \u641C\u7D22\u5173\u952E\u4EE3\u7801\u5B9E\u73B0
2435
2435
 
2436
2436
  **\u7B2C\u4E8C\u6B65\uFF1A\u7ED9\u51FA\u8BC4\u5BA1\u610F\u89C1**
2437
- \u6536\u96C6\u5B8C\u4FE1\u606F\u540E\uFF0C\u7528 Markdown \u683C\u5F0F\u8F93\u51FA\u8BC4\u5BA1\u7ED3\u679C\uFF08\u4E0D\u8981\u8F93\u51FA JSON\uFF09\u3002`,t}var hC={approvalThreshold:2,allowConcernPass:true,rejectBlocks:true},Eo=class{config;constructor(e){this.config={...hC,...e};}aggregate(e,t,s){let n=Date.now(),r=this.countVotes(e),i=this.determineApproval(r),o=this.calculateConfidence(e,r),l=this.mergeRisks(e),c=this.mergeSuggestions(e),u=this.estimateEffort(e),d=this.generateRecommendation(e,i),p=this.collectRequiredChanges(e,i);return {id:t,approved:i,confidence:o,reviews:e,summary:{risks:l,suggestions:c,estimatedEffort:u,recommendedApproach:d},requiredChanges:p.length>0?p:void 0,startedAt:s,completedAt:n,totalDuration:n-s}}countVotes(e){let t={approve:0,concern:0,reject:0,total:e.length};for(let s of e)t[s.verdict]++;return t}determineApproval(e){return this.config.rejectBlocks&&e.reject>0?false:e.approve>=this.config.approvalThreshold?true:this.config.allowConcernPass?e.approve+e.concern>=this.config.approvalThreshold:false}calculateConfidence(e,t){let s=t.approve/t.total*100,n=t.concern*10,r=t.reject*25,i=t.approve===t.total||t.reject===t.total?10:0,o=Math.max(0,Math.min(100,s-n-r+i));return Math.round(o)}mergeRisks(e){let t=new Map;for(let n of e)for(let r of n.risks){let i=r.toLowerCase().substring(0,50);t.has(i)||t.set(i,{level:this.inferRiskLevel(r,n.verdict),description:r,mitigation:this.findMitigation(r,n.suggestions),sourceAgentId:n.agentId});}let s={critical:0,high:1,medium:2,low:3};return Array.from(t.values()).sort((n,r)=>s[n.level]-s[r.level])}inferRiskLevel(e,t){let s=e.toLowerCase();return s.includes("critical")||s.includes("\u4E25\u91CD")||s.includes("\u81F4\u547D")?"critical":s.includes("high")||s.includes("\u9AD8")||s.includes("\u91CD\u5927")?"high":s.includes("low")||s.includes("\u4F4E")||s.includes("\u8F7B\u5FAE")?"low":t==="reject"?"high":"medium"}findMitigation(e,t){for(let s of t)if(s.toLowerCase().includes(e.substring(0,20).toLowerCase()))return s;return "\u5F85\u5B9A"}mergeSuggestions(e){let t=new Set;for(let s of e)for(let n of s.suggestions)n.trim()&&t.add(n.trim());return Array.from(t)}estimateEffort(e){let t=e.reduce((r,i)=>r+i.tokenUsed,0),s=e.reduce((r,i)=>r+i.duration,0)/e.length,n="medium";return s<5e3&&(n="low"),s>15e3&&(n="high"),{timeRange:n==="low"?"1-2 hours":n==="high"?"4-8 hours":"2-4 hours",complexity:n,parallelism:n==="high"?4:n==="medium"?3:2,estimatedTokens:Math.round(t*5)}}generateRecommendation(e,t){if(!t){let n=e.find(r=>r.verdict==="reject");return n?`\u65B9\u6848\u9700\u8981\u8C03\u6574:
2437
+ \u6536\u96C6\u5B8C\u4FE1\u606F\u540E\uFF0C\u7528 Markdown \u683C\u5F0F\u8F93\u51FA\u8BC4\u5BA1\u7ED3\u679C\uFF08\u4E0D\u8981\u8F93\u51FA JSON\uFF09\u3002`,t}var fC={approvalThreshold:2,allowConcernPass:true,rejectBlocks:true},Eo=class{config;constructor(e){this.config={...fC,...e};}aggregate(e,t,s){let n=Date.now(),r=this.countVotes(e),i=this.determineApproval(r),o=this.calculateConfidence(e,r),l=this.mergeRisks(e),c=this.mergeSuggestions(e),u=this.estimateEffort(e),d=this.generateRecommendation(e,i),p=this.collectRequiredChanges(e,i);return {id:t,approved:i,confidence:o,reviews:e,summary:{risks:l,suggestions:c,estimatedEffort:u,recommendedApproach:d},requiredChanges:p.length>0?p:void 0,startedAt:s,completedAt:n,totalDuration:n-s}}countVotes(e){let t={approve:0,concern:0,reject:0,total:e.length};for(let s of e)t[s.verdict]++;return t}determineApproval(e){return this.config.rejectBlocks&&e.reject>0?false:e.approve>=this.config.approvalThreshold?true:this.config.allowConcernPass?e.approve+e.concern>=this.config.approvalThreshold:false}calculateConfidence(e,t){let s=t.approve/t.total*100,n=t.concern*10,r=t.reject*25,i=t.approve===t.total||t.reject===t.total?10:0,o=Math.max(0,Math.min(100,s-n-r+i));return Math.round(o)}mergeRisks(e){let t=new Map;for(let n of e)for(let r of n.risks){let i=r.toLowerCase().substring(0,50);t.has(i)||t.set(i,{level:this.inferRiskLevel(r,n.verdict),description:r,mitigation:this.findMitigation(r,n.suggestions),sourceAgentId:n.agentId});}let s={critical:0,high:1,medium:2,low:3};return Array.from(t.values()).sort((n,r)=>s[n.level]-s[r.level])}inferRiskLevel(e,t){let s=e.toLowerCase();return s.includes("critical")||s.includes("\u4E25\u91CD")||s.includes("\u81F4\u547D")?"critical":s.includes("high")||s.includes("\u9AD8")||s.includes("\u91CD\u5927")?"high":s.includes("low")||s.includes("\u4F4E")||s.includes("\u8F7B\u5FAE")?"low":t==="reject"?"high":"medium"}findMitigation(e,t){for(let s of t)if(s.toLowerCase().includes(e.substring(0,20).toLowerCase()))return s;return "\u5F85\u5B9A"}mergeSuggestions(e){let t=new Set;for(let s of e)for(let n of s.suggestions)n.trim()&&t.add(n.trim());return Array.from(t)}estimateEffort(e){let t=e.reduce((r,i)=>r+i.tokenUsed,0),s=e.reduce((r,i)=>r+i.duration,0)/e.length,n="medium";return s<5e3&&(n="low"),s>15e3&&(n="high"),{timeRange:n==="low"?"1-2 hours":n==="high"?"4-8 hours":"2-4 hours",complexity:n,parallelism:n==="high"?4:n==="medium"?3:2,estimatedTokens:Math.round(t*5)}}generateRecommendation(e,t){if(!t){let n=e.find(r=>r.verdict==="reject");return n?`\u65B9\u6848\u9700\u8981\u8C03\u6574:
2438
2438
  ${n.analysis}`:"\u65B9\u6848\u9700\u8981\u8FDB\u4E00\u6B65\u8BA8\u8BBA"}let s=e.filter(n=>n.verdict==="approve");return s.length>0?`\u65B9\u6848\u53EF\u884C\u3002
2439
- ${s[0].analysis}`:"\u65B9\u6848\u57FA\u672C\u53EF\u884C\uFF0C\u4F46\u9700\u6CE8\u610F\u76F8\u5173\u98CE\u9669"}collectRequiredChanges(e,t){let s=[];for(let n of e)n.verdict==="reject"?s.push({description:n.analysis,priority:"must",sourceAgentId:n.agentId}):n.verdict==="concern"&&n.risks.length>0&&s.push({description:n.risks[0],priority:"should",sourceAgentId:n.agentId});return s}};function Io(a){return new Eo(a)}W();var fC={parallelReview:true,timeout:6e4,approvalThreshold:2,allowConcernPass:true},Tn=2,Mo=class{llmCall;config;onEvent;aggregator;agents;workerModels;defaultModel;constructor(e){this.llmCall=e.llmCall,this.config={...fC,...e.config},this.onEvent=e.onEvent,this.workerModels=e.workerModels??[],this.defaultModel=e.defaultModel??"default",this.aggregator=Io({approvalThreshold:this.config.approvalThreshold,allowConcernPass:this.config.allowConcernPass}),this.agents=this.config.customAgents?this.mergeAgents(Ao,this.config.customAgents):Ao;}async review(e){let t=this.generateReviewId(),s=Date.now();this.emitEvent({type:"ccb_review_start",timestamp:s,data:{reviewId:t}});try{let n=this.assignWorkerModelsToAgents(),r=this.config.parallelReview?await this.parallelReviewWithAgents(e,t,n):await this.sequentialReviewWithAgents(e,t,n);this.emitEvent({type:"ccb_review_aggregating",timestamp:Date.now(),data:{reviewId:t}});let i=this.aggregator.aggregate(r,t,s);return this.emitEvent({type:"ccb_review_complete",timestamp:Date.now(),data:{reviewId:t,result:i}}),i}catch(n){return console.error("[CCBOrchestrator] Review failed, using fallback",n),this.createFallbackResult(t,s)}}assignWorkerModelsToAgents(){return this.workerModels.length===0?this.agents.map(e=>({...e,model:this.defaultModel})):this.agents.map((e,t)=>{let s=this.workerModels[t%this.workerModels.length],n=`${s.providerId}:${s.model}`;return {...e,model:n}})}async quickReview(e){let t=this.generateReviewId(),s=Date.now();this.emitEvent({type:"ccb_review_start",timestamp:s,data:{reviewId:t}});try{let n=this.agents.find(l=>l.perspective==="implementation");if(!n)throw new Error("No implementer agent found");let r=await this.executeAgentReview(n,e,t),o=Io({approvalThreshold:1,allowConcernPass:!0,rejectBlocks:!0}).aggregate([r],t,s);return this.emitEvent({type:"ccb_review_complete",timestamp:Date.now(),data:{reviewId:t,result:o}}),o}catch(n){return console.error("[CCBOrchestrator] Quick review failed",n),this.createFallbackResult(t,s)}}async multiRoleReview(e){let t=this.generateReviewId(),s=Date.now();this.emitEvent({type:"ccb_review_start",timestamp:s,data:{reviewId:t}});try{let n=this.agents.map(o=>({...o,model:this.defaultModel})),r=this.config.parallelReview?await this.parallelReviewWithAgents(e,t,n):await this.sequentialReviewWithAgents(e,t,n);this.emitEvent({type:"ccb_review_aggregating",timestamp:Date.now(),data:{reviewId:t}});let i=this.aggregator.aggregate(r,t,s);return this.emitEvent({type:"ccb_review_complete",timestamp:Date.now(),data:{reviewId:t,result:i}}),i}catch(n){return console.error("[CCBOrchestrator] Multi-role review failed, using fallback",n),this.createFallbackResult(t,s)}}async parallelReviewWithAgents(e,t,s){let n=s.map(i=>this.executeAgentReviewWithTimeout(i,e,t));return (await Promise.allSettled(n)).filter(i=>i.status==="fulfilled").map(i=>i.value)}async sequentialReviewWithAgents(e,t,s){let n=[];for(let r of s)try{let i=await this.executeAgentReviewWithTimeout(r,e,t);n.push(i);}catch(i){console.warn(`[CCBOrchestrator] Agent ${r.id} failed`,i);}return n}async parallelReview(e,t){let s=this.agents.map(r=>this.executeAgentReviewWithTimeout(r,e,t));return (await Promise.allSettled(s)).filter(r=>r.status==="fulfilled").map(r=>r.value)}async sequentialReview(e,t){let s=[];for(let n of this.agents)try{let r=await this.executeAgentReviewWithTimeout(n,e,t);s.push(r);}catch(r){console.warn(`[CCBOrchestrator] Agent ${n.id} failed`,r);}return s}async executeAgentReviewWithTimeout(e,t,s){let n=null;for(let r=0;r<=Tn;r++)try{return r>0&&(m.warn("CCB",`Retrying agent ${e.id} review (attempt ${r}/${Tn})`,{agentId:e.id,agentName:e.name,model:e.model,error:n?.message}),this.emitEvent({type:"ccb_agent_retry",timestamp:Date.now(),data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective,model:e.model,retryCount:r,maxRetries:Tn,error:n?.message,willRetry:!0}}),await new Promise(o=>setTimeout(o,1e3*r))),await new Promise((o,l)=>{let c=setTimeout(()=>{l(new Error(`Agent ${e.id} review timeout after ${this.config.timeout}ms`));},this.config.timeout);this.executeAgentReview(e,t,s).then(u=>{clearTimeout(c),o(u);}).catch(u=>{clearTimeout(c),l(u);});})}catch(i){if(n=i instanceof Error?i:new Error(String(i)),m.error("CCB",`Agent ${e.id} review failed (attempt ${r+1}/${Tn+1})`,{agentId:e.id,agentName:e.name,model:e.model,error:n.message}),r>=Tn)throw m.error("CCB",`Agent ${e.id} review failed after all retries`,{agentId:e.id,agentName:e.name,model:e.model,totalAttempts:r+1,error:n.message}),this.emitEvent({type:"ccb_agent_failed",timestamp:Date.now(),data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective,model:e.model,retryCount:r,maxRetries:Tn,error:n.message,willRetry:false}}),n}throw n||new Error("Unknown error")}async executeAgentReview(e,t,s){let n=Date.now();this.emitEvent({type:"ccb_agent_spawned",timestamp:n,data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective}}),this.emitEvent({type:"ccb_agent_thinking",timestamp:Date.now(),data:{reviewId:s,agentId:e.id,progress:0}});let r=rc(t,e),i=await this.llmCall(e.systemPrompt,r,e.model),o=this.parseAgentResponse(i,e),l=Date.now();this.emitEvent({type:"ccb_agent_verdict",timestamp:l,data:{reviewId:s,agentId:e.id,verdict:o.verdict}});let c={agentId:e.id,perspective:e.perspective,model:e.model,verdict:o.verdict,analysis:o.analysis,risks:o.risks,suggestions:o.suggestions,duration:l-n,tokenUsed:this.estimateTokens(i)};return this.emitEvent({type:"ccb_agent_review",timestamp:l,data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective,model:e.model,verdict:o.verdict,analysis:o.analysis,risks:o.risks,suggestions:o.suggestions}}),this.emitEvent({type:"ccb_agent_completed",timestamp:l,data:{reviewId:s,agentId:e.id}}),c}parseAgentResponse(e,t){if(process.env.CLI_DEBUG==="1"&&console.log(`[CCB] Agent ${t.id} raw response:`,e?.substring(0,500)),/\*\*(?:判定|verdict|分析|analysis|风险|risks?|建议|suggestions?)\*\*/i.test(e))return process.env.CLI_DEBUG==="1"&&console.log(`[CCB] Agent ${t.id} using Markdown parser`),this.parseMarkdownResponse(e,t);try{let n=null,r=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(r&&(n=r[1].trim()),!n){let d=e.match(/\{[\s\S]*\}/);d&&(n=d[0]);}if(!n)return this.parseMarkdownResponse(e,t);let i=JSON.parse(n);process.env.CLI_DEBUG==="1"&&console.log(`[CCB] Agent ${t.id} parsed keys:`,Object.keys(i));let o=this.extractVerdict(i),l=this.extractAnalysis(i,e),c=this.extractRisks(i),u=this.extractSuggestions(i);return {verdict:o,analysis:l,risks:c,suggestions:u}}catch(n){return process.env.CLI_DEBUG==="1"&&(console.log(`[CCB] Agent ${t.id} parse failed:`,n?.message),console.log("[CCB] Response preview:",e?.substring(0,300))),this.parseMarkdownResponse(e,t)}}extractVerdict(e){if(e.verdict)return this.normalizeVerdict(e.verdict);if(e.status){let t=String(e.status).toLowerCase();if(t.includes("reject")||t.includes("denied"))return "reject";if(t.includes("concern")||t.includes("warning")||t.includes("notes"))return "concern";if(t.includes("approve")||t.includes("pass")||t.includes("ok"))return "approve"}if(Array.isArray(e.reviewers)){let t=e.reviewers.map(r=>r.status||r.verdict||""),s=t.some(r=>r.toLowerCase().includes("reject")),n=t.some(r=>r.toLowerCase().includes("concern")||r.toLowerCase().includes("notes"));return s?"reject":n?"concern":"approve"}return e.decision?this.normalizeVerdict(e.decision):"approve"}extractAnalysis(e,t){let s=[],n=["analysis","summary","description","comment","review","conclusion"];for(let r of n)if(e[r]&&typeof e[r]=="string"){s.push(e[r]);break}if(e.assessment){if(typeof e.assessment=="string")s.push(e.assessment);else if(typeof e.assessment=="object"){let r=e.assessment.summary||e.assessment.description||e.assessment.text;r&&s.push(r);}}if(e.architecture&&typeof e.architecture=="object"&&(e.architecture.assessment&&s.push(`**\u67B6\u6784\u8BC4\u4F30:** ${e.architecture.assessment}`),Array.isArray(e.architecture.focus)&&s.push(`**\u5173\u6CE8\u70B9:** ${e.architecture.focus.join(", ")}`)),e.projectContext&&typeof e.projectContext=="object"){let r=e.projectContext,i=[];r.frontend&&i.push(`\u524D\u7AEF: ${r.frontend}`),r.backend&&i.push(`\u540E\u7AEF: ${r.backend}`),r.database&&i.push(`\u6570\u636E\u5E93: ${r.database}`),i.length>0&&s.push(`**\u9879\u76EE\u6280\u672F\u6808:** ${i.join(" | ")}`),r.notes&&s.push(`**\u5907\u6CE8:** ${r.notes}`);}if(Array.isArray(e.reviewers))for(let r of e.reviewers){let i=r.name||r.role||"\u8BC4\u5BA1\u5B98";r.status||r.verdict||"";if(r.findings){let l=r.findings;Array.isArray(l.strengths)&&l.strengths.length>0&&(s.push(`**${i} - \u4F18\u70B9:**`),l.strengths.slice(0,3).forEach(u=>{let d=typeof u=="string"?u:u.description||JSON.stringify(u);s.push(` \u2705 ${d}`);}));let c=l.concerns||l.weaknesses||l.issues;Array.isArray(c)&&c.length>0&&(s.push(`**${i} - \u5173\u6CE8\u70B9:**`),c.slice(0,3).forEach(u=>{let d=typeof u=="string"?u:u.description||JSON.stringify(u);s.push(` \u26A0\uFE0F ${d}`);}));}}if(s.length===0){let r=["verdict","status","risks","suggestions","recommendations"],i=Object.keys(e).filter(o=>!r.includes(o));for(let o of i.slice(0,5)){let l=e[o];typeof l=="string"&&l.length>0&&l.length<500&&s.push(`**${this.formatKeyName(o)}:** ${l}`);}}return s.length===0?t.replace(/```json[\s\S]*?```/g,"").trim().substring(0,500):s.join(`
2439
+ ${s[0].analysis}`:"\u65B9\u6848\u57FA\u672C\u53EF\u884C\uFF0C\u4F46\u9700\u6CE8\u610F\u76F8\u5173\u98CE\u9669"}collectRequiredChanges(e,t){let s=[];for(let n of e)n.verdict==="reject"?s.push({description:n.analysis,priority:"must",sourceAgentId:n.agentId}):n.verdict==="concern"&&n.risks.length>0&&s.push({description:n.risks[0],priority:"should",sourceAgentId:n.agentId});return s}};function Io(a){return new Eo(a)}W();var yC={parallelReview:true,timeout:6e4,approvalThreshold:2,allowConcernPass:true},Tn=2,Mo=class{llmCall;config;onEvent;aggregator;agents;workerModels;defaultModel;constructor(e){this.llmCall=e.llmCall,this.config={...yC,...e.config},this.onEvent=e.onEvent,this.workerModels=e.workerModels??[],this.defaultModel=e.defaultModel??"default",this.aggregator=Io({approvalThreshold:this.config.approvalThreshold,allowConcernPass:this.config.allowConcernPass}),this.agents=this.config.customAgents?this.mergeAgents(Ao,this.config.customAgents):Ao;}async review(e){let t=this.generateReviewId(),s=Date.now();this.emitEvent({type:"ccb_review_start",timestamp:s,data:{reviewId:t}});try{let n=this.assignWorkerModelsToAgents(),r=this.config.parallelReview?await this.parallelReviewWithAgents(e,t,n):await this.sequentialReviewWithAgents(e,t,n);this.emitEvent({type:"ccb_review_aggregating",timestamp:Date.now(),data:{reviewId:t}});let i=this.aggregator.aggregate(r,t,s);return this.emitEvent({type:"ccb_review_complete",timestamp:Date.now(),data:{reviewId:t,result:i}}),i}catch(n){return console.error("[CCBOrchestrator] Review failed, using fallback",n),this.createFallbackResult(t,s)}}assignWorkerModelsToAgents(){return this.workerModels.length===0?this.agents.map(e=>({...e,model:this.defaultModel})):this.agents.map((e,t)=>{let s=this.workerModels[t%this.workerModels.length],n=`${s.providerId}:${s.model}`;return {...e,model:n}})}async quickReview(e){let t=this.generateReviewId(),s=Date.now();this.emitEvent({type:"ccb_review_start",timestamp:s,data:{reviewId:t}});try{let n=this.agents.find(l=>l.perspective==="implementation");if(!n)throw new Error("No implementer agent found");let r=await this.executeAgentReview(n,e,t),o=Io({approvalThreshold:1,allowConcernPass:!0,rejectBlocks:!0}).aggregate([r],t,s);return this.emitEvent({type:"ccb_review_complete",timestamp:Date.now(),data:{reviewId:t,result:o}}),o}catch(n){return console.error("[CCBOrchestrator] Quick review failed",n),this.createFallbackResult(t,s)}}async multiRoleReview(e){let t=this.generateReviewId(),s=Date.now();this.emitEvent({type:"ccb_review_start",timestamp:s,data:{reviewId:t}});try{let n=this.agents.map(o=>({...o,model:this.defaultModel})),r=this.config.parallelReview?await this.parallelReviewWithAgents(e,t,n):await this.sequentialReviewWithAgents(e,t,n);this.emitEvent({type:"ccb_review_aggregating",timestamp:Date.now(),data:{reviewId:t}});let i=this.aggregator.aggregate(r,t,s);return this.emitEvent({type:"ccb_review_complete",timestamp:Date.now(),data:{reviewId:t,result:i}}),i}catch(n){return console.error("[CCBOrchestrator] Multi-role review failed, using fallback",n),this.createFallbackResult(t,s)}}async parallelReviewWithAgents(e,t,s){let n=s.map(i=>this.executeAgentReviewWithTimeout(i,e,t));return (await Promise.allSettled(n)).filter(i=>i.status==="fulfilled").map(i=>i.value)}async sequentialReviewWithAgents(e,t,s){let n=[];for(let r of s)try{let i=await this.executeAgentReviewWithTimeout(r,e,t);n.push(i);}catch(i){console.warn(`[CCBOrchestrator] Agent ${r.id} failed`,i);}return n}async parallelReview(e,t){let s=this.agents.map(r=>this.executeAgentReviewWithTimeout(r,e,t));return (await Promise.allSettled(s)).filter(r=>r.status==="fulfilled").map(r=>r.value)}async sequentialReview(e,t){let s=[];for(let n of this.agents)try{let r=await this.executeAgentReviewWithTimeout(n,e,t);s.push(r);}catch(r){console.warn(`[CCBOrchestrator] Agent ${n.id} failed`,r);}return s}async executeAgentReviewWithTimeout(e,t,s){let n=null;for(let r=0;r<=Tn;r++)try{return r>0&&(m.warn("CCB",`Retrying agent ${e.id} review (attempt ${r}/${Tn})`,{agentId:e.id,agentName:e.name,model:e.model,error:n?.message}),this.emitEvent({type:"ccb_agent_retry",timestamp:Date.now(),data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective,model:e.model,retryCount:r,maxRetries:Tn,error:n?.message,willRetry:!0}}),await new Promise(o=>setTimeout(o,1e3*r))),await new Promise((o,l)=>{let c=setTimeout(()=>{l(new Error(`Agent ${e.id} review timeout after ${this.config.timeout}ms`));},this.config.timeout);this.executeAgentReview(e,t,s).then(u=>{clearTimeout(c),o(u);}).catch(u=>{clearTimeout(c),l(u);});})}catch(i){if(n=i instanceof Error?i:new Error(String(i)),m.error("CCB",`Agent ${e.id} review failed (attempt ${r+1}/${Tn+1})`,{agentId:e.id,agentName:e.name,model:e.model,error:n.message}),r>=Tn)throw m.error("CCB",`Agent ${e.id} review failed after all retries`,{agentId:e.id,agentName:e.name,model:e.model,totalAttempts:r+1,error:n.message}),this.emitEvent({type:"ccb_agent_failed",timestamp:Date.now(),data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective,model:e.model,retryCount:r,maxRetries:Tn,error:n.message,willRetry:false}}),n}throw n||new Error("Unknown error")}async executeAgentReview(e,t,s){let n=Date.now();this.emitEvent({type:"ccb_agent_spawned",timestamp:n,data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective}}),this.emitEvent({type:"ccb_agent_thinking",timestamp:Date.now(),data:{reviewId:s,agentId:e.id,progress:0}});let r=rc(t,e),i=await this.llmCall(e.systemPrompt,r,e.model),o=this.parseAgentResponse(i,e),l=Date.now();this.emitEvent({type:"ccb_agent_verdict",timestamp:l,data:{reviewId:s,agentId:e.id,verdict:o.verdict}});let c={agentId:e.id,perspective:e.perspective,model:e.model,verdict:o.verdict,analysis:o.analysis,risks:o.risks,suggestions:o.suggestions,duration:l-n,tokenUsed:this.estimateTokens(i)};return this.emitEvent({type:"ccb_agent_review",timestamp:l,data:{reviewId:s,agentId:e.id,agentName:e.name,perspective:e.perspective,model:e.model,verdict:o.verdict,analysis:o.analysis,risks:o.risks,suggestions:o.suggestions}}),this.emitEvent({type:"ccb_agent_completed",timestamp:l,data:{reviewId:s,agentId:e.id}}),c}parseAgentResponse(e,t){if(process.env.CLI_DEBUG==="1"&&console.log(`[CCB] Agent ${t.id} raw response:`,e?.substring(0,500)),/\*\*(?:判定|verdict|分析|analysis|风险|risks?|建议|suggestions?)\*\*/i.test(e))return process.env.CLI_DEBUG==="1"&&console.log(`[CCB] Agent ${t.id} using Markdown parser`),this.parseMarkdownResponse(e,t);try{let n=null,r=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(r&&(n=r[1].trim()),!n){let d=e.match(/\{[\s\S]*\}/);d&&(n=d[0]);}if(!n)return this.parseMarkdownResponse(e,t);let i=JSON.parse(n);process.env.CLI_DEBUG==="1"&&console.log(`[CCB] Agent ${t.id} parsed keys:`,Object.keys(i));let o=this.extractVerdict(i),l=this.extractAnalysis(i,e),c=this.extractRisks(i),u=this.extractSuggestions(i);return {verdict:o,analysis:l,risks:c,suggestions:u}}catch(n){return process.env.CLI_DEBUG==="1"&&(console.log(`[CCB] Agent ${t.id} parse failed:`,n?.message),console.log("[CCB] Response preview:",e?.substring(0,300))),this.parseMarkdownResponse(e,t)}}extractVerdict(e){if(e.verdict)return this.normalizeVerdict(e.verdict);if(e.status){let t=String(e.status).toLowerCase();if(t.includes("reject")||t.includes("denied"))return "reject";if(t.includes("concern")||t.includes("warning")||t.includes("notes"))return "concern";if(t.includes("approve")||t.includes("pass")||t.includes("ok"))return "approve"}if(Array.isArray(e.reviewers)){let t=e.reviewers.map(r=>r.status||r.verdict||""),s=t.some(r=>r.toLowerCase().includes("reject")),n=t.some(r=>r.toLowerCase().includes("concern")||r.toLowerCase().includes("notes"));return s?"reject":n?"concern":"approve"}return e.decision?this.normalizeVerdict(e.decision):"approve"}extractAnalysis(e,t){let s=[],n=["analysis","summary","description","comment","review","conclusion"];for(let r of n)if(e[r]&&typeof e[r]=="string"){s.push(e[r]);break}if(e.assessment){if(typeof e.assessment=="string")s.push(e.assessment);else if(typeof e.assessment=="object"){let r=e.assessment.summary||e.assessment.description||e.assessment.text;r&&s.push(r);}}if(e.architecture&&typeof e.architecture=="object"&&(e.architecture.assessment&&s.push(`**\u67B6\u6784\u8BC4\u4F30:** ${e.architecture.assessment}`),Array.isArray(e.architecture.focus)&&s.push(`**\u5173\u6CE8\u70B9:** ${e.architecture.focus.join(", ")}`)),e.projectContext&&typeof e.projectContext=="object"){let r=e.projectContext,i=[];r.frontend&&i.push(`\u524D\u7AEF: ${r.frontend}`),r.backend&&i.push(`\u540E\u7AEF: ${r.backend}`),r.database&&i.push(`\u6570\u636E\u5E93: ${r.database}`),i.length>0&&s.push(`**\u9879\u76EE\u6280\u672F\u6808:** ${i.join(" | ")}`),r.notes&&s.push(`**\u5907\u6CE8:** ${r.notes}`);}if(Array.isArray(e.reviewers))for(let r of e.reviewers){let i=r.name||r.role||"\u8BC4\u5BA1\u5B98";r.status||r.verdict||"";if(r.findings){let l=r.findings;Array.isArray(l.strengths)&&l.strengths.length>0&&(s.push(`**${i} - \u4F18\u70B9:**`),l.strengths.slice(0,3).forEach(u=>{let d=typeof u=="string"?u:u.description||JSON.stringify(u);s.push(` \u2705 ${d}`);}));let c=l.concerns||l.weaknesses||l.issues;Array.isArray(c)&&c.length>0&&(s.push(`**${i} - \u5173\u6CE8\u70B9:**`),c.slice(0,3).forEach(u=>{let d=typeof u=="string"?u:u.description||JSON.stringify(u);s.push(` \u26A0\uFE0F ${d}`);}));}}if(s.length===0){let r=["verdict","status","risks","suggestions","recommendations"],i=Object.keys(e).filter(o=>!r.includes(o));for(let o of i.slice(0,5)){let l=e[o];typeof l=="string"&&l.length>0&&l.length<500&&s.push(`**${this.formatKeyName(o)}:** ${l}`);}}return s.length===0?t.replace(/```json[\s\S]*?```/g,"").trim().substring(0,500):s.join(`
2440
2440
  `)}extractRisks(e){let t=[],s=["risks","concerns","issues","warnings","problems"];for(let n of s)Array.isArray(e[n])&&e[n].forEach(r=>{let i=typeof r=="string"?r:r.description||r.message||r.text||"";i&&!t.includes(i)&&t.push(i);});if(e.architecture?.risks&&Array.isArray(e.architecture.risks)&&e.architecture.risks.forEach(n=>{let r=typeof n=="string"?n:n.description||n.message||"";r&&!t.includes(r)&&t.push(r);}),Array.isArray(e.reviewers))for(let n of e.reviewers){let r=n.findings||{},i=r.concerns||r.risks||r.issues||[];Array.isArray(i)&&i.forEach(o=>{let l=typeof o=="string"?o:o.description||o.message||"";l&&!t.includes(l)&&t.push(l);});}return t.slice(0,10)}extractSuggestions(e){let t=[],s=["suggestions","recommendations","improvements","alternatives","optimizations","bestPractices"];for(let n of s)Array.isArray(e[n])&&e[n].forEach(r=>{let i=typeof r=="string"?r:r.description||r.message||r.text||"";i&&!t.includes(i)&&t.push(i);});if(e.architecture?.recommendations&&Array.isArray(e.architecture.recommendations)&&e.architecture.recommendations.forEach(n=>{let r=typeof n=="string"?n:n.description||n.message||"";r&&!t.includes(r)&&t.push(r);}),Array.isArray(e.reviewers))for(let n of e.reviewers){let r=n.findings||{},i=r.suggestions||r.recommendations||[];Array.isArray(i)&&i.forEach(o=>{let l=typeof o=="string"?o:o.description||o.message||"";l&&!t.includes(l)&&t.push(l);});}return t.slice(0,10)}formatKeyName(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}formatNestedObject(e){if(typeof e=="string")return e;if(e==null)return "";if(typeof e!="object")return String(e);let t=[];for(let[s,n]of Object.entries(e)){if(s.startsWith("_"))continue;let r=s.replace(/([A-Z])/g," $1").replace(/^./,i=>i.toUpperCase());Array.isArray(n)?n.length>0&&(t.push(`**${r}:**`),n.forEach((i,o)=>{typeof i=="string"?t.push(` ${o+1}. ${i}`):typeof i=="object"&&i!==null&&t.push(` ${o+1}. ${i.description||i.name||JSON.stringify(i)}`);})):typeof n=="object"&&n!==null?t.push(`**${r}:** ${this.formatNestedObject(n)}`):n!=null&&n!==""&&t.push(`**${r}:** ${n}`);}return t.join(`
2441
2441
  `)}parseMarkdownResponse(e,t){let s="approve",n=e.match(/\*\*(?:判定|verdict|结论|decision)\*\*\s*[::]\s*(\w+)/i);n?s=this.normalizeVerdict(n[1]):s=this.inferVerdict(e);let r="",i=e.match(/\*\*(?:分析|analysis|评估|assessment)\*\*\s*[::]\s*\n?([\s\S]*?)(?=\*\*(?:风险|建议|risks?|suggestions?)\*\*|$)/i);i&&(r=i[1].trim()),r||(r=e.replace(/\*\*(?:判定|verdict|结论|decision)\*\*\s*[::]\s*\w+/gi,"").replace(/\*\*(?:风险|risks?)\*\*\s*[::][\s\S]*?(?=\*\*|$)/gi,"").replace(/\*\*(?:建议|suggestions?|recommendations?)\*\*\s*[::][\s\S]*?(?=\*\*|$)/gi,"").replace(/```json[\s\S]*?```/g,"").replace(/\{[\s\S]*?\}/g,"").replace(/---+/g,"").trim()),r.length>800&&(r=r.substring(0,800)+"...");let o=[],l=e.match(/\*\*(?:风险|risks?|concerns?|issues?)\*\*\s*[::]\s*\n?((?:\s*[-•*]\s*.+\n?)+)/gi);l&&l.forEach(d=>{let p=d.match(/[-•*]\s*\[?([^\]\n]+)\]?/g);p&&p.forEach(h=>{let g=h.replace(/^[-•*]\s*\[?/,"").replace(/\]?$/,"").trim();g&&!o.includes(g)&&g.length>2&&o.push(g);});});let c=[],u=e.match(/\*\*(?:建议|suggestions?|recommendations?)\*\*\s*[::]\s*\n?((?:\s*[-•*]\s*.+\n?)+)/gi);return u&&u.forEach(d=>{let p=d.match(/[-•*]\s*\[?([^\]\n]+)\]?/g);p&&p.forEach(h=>{let g=h.replace(/^[-•*]\s*\[?/,"").replace(/\]?$/,"").trim();g&&!c.includes(g)&&g.length>2&&c.push(g);});}),{verdict:s,analysis:r,risks:o,suggestions:c}}normalizeVerdict(e){let t=(e||"").toLowerCase();return t.includes("reject")||t==="reject"?"reject":t.includes("concern")||t==="concern"?"concern":"approve"}inferVerdict(e){let t=e.toLowerCase();return t.includes("reject")||t.includes("\u4E0D\u53EF\u884C")||t.includes("\u62D2\u7EDD")?"reject":t.includes("concern")||t.includes("\u62C5\u5FE7")||t.includes("\u98CE\u9669")?"concern":"approve"}estimateTokens(e){let t=(e.match(/[\u4e00-\u9fa5]/g)||[]).length,s=e.length-t;return Math.round(t/2+s/4)}generateReviewId(){return `ccb-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}mergeAgents(e,t){let s=[...e];for(let n of t){let r=s.findIndex(i=>i.id===n.id);r>=0&&(s[r]={...s[r],...n});}return s}createFallbackResult(e,t){let s=Date.now();return {id:e,approved:true,confidence:30,reviews:[],summary:{risks:[{level:"medium",description:"CCB \u8BC4\u5BA1\u5931\u8D25\uFF0C\u4F7F\u7528\u964D\u7EA7\u7B56\u7565",mitigation:"\u5EFA\u8BAE\u624B\u52A8\u8BC4\u5BA1",sourceAgentId:"system"}],suggestions:["\u5EFA\u8BAE\u8FDB\u884C\u624B\u52A8\u8BC4\u5BA1"],estimatedEffort:{timeRange:"\u672A\u77E5",complexity:"medium",parallelism:2,estimatedTokens:1e4},recommendedApproach:"\u5EFA\u8BAE\u8C28\u614E\u6267\u884C"},startedAt:t,completedAt:s,totalDuration:s-t}}emitEvent(e){this.onEvent&&this.onEvent(e);}updateConfig(e){this.config={...this.config,...e};}setEventHandler(e){this.onEvent=e;}};function ic(a){return new Mo(a)}W();var Po=class{config;constructor(e){this.config={workDir:e.workDir,maxFiles:e.maxFiles??10,maxContentLength:e.maxContentLength??5e3};}async collect(e){let t=Date.now();m.info("CCB_CONTEXT","Collecting project context",{workDir:this.config.workDir});let s={rootDir:this.config.workDir,projectName:this.getProjectName(),techStack:this.detectTechStack(),directoryStructure:this.getDirectoryStructure(),keyFiles:this.findKeyFiles()};s.dependencies=this.getPackageDependencies(),s.readmeSummary=this.getReadmeSummary(),s.relevantCode=await this.findRelevantCode(e);let n=Date.now()-t;return m.info("CCB_CONTEXT",`Context collected in ${n}ms`,{projectName:s.projectName,techStack:s.techStack,keyFilesCount:s.keyFiles.length}),s}getProjectName(){try{let e=te.join(this.config.workDir,"package.json");if(Me.existsSync(e))return JSON.parse(Me.readFileSync(e,"utf-8")).name||te.basename(this.config.workDir)}catch{}return te.basename(this.config.workDir)}detectTechStack(){let e=[],t=this.config.workDir,s=te.join(t,"package.json");if(Me.existsSync(s))try{let n=JSON.parse(Me.readFileSync(s,"utf-8")),r={...n.dependencies,...n.devDependencies};r.react&&e.push("React"),r.vue&&e.push("Vue"),r.next&&e.push("Next.js"),r.express&&e.push("Express"),(r.typescript||Me.existsSync(te.join(t,"tsconfig.json")))&&e.push("TypeScript"),(r.prisma||r["@prisma/client"])&&e.push("Prisma"),r.mongoose&&e.push("MongoDB"),(r.pg||r.postgres)&&e.push("PostgreSQL"),r.tailwindcss&&e.push("TailwindCSS"),r.electron&&e.push("Electron");}catch{}return (Me.existsSync(te.join(t,"requirements.txt"))||Me.existsSync(te.join(t,"pyproject.toml")))&&e.push("Python"),Me.existsSync(te.join(t,"go.mod"))&&e.push("Go"),Me.existsSync(te.join(t,"Cargo.toml"))&&e.push("Rust"),e.length>0?e:["Unknown"]}getDirectoryStructure(){let t=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv"]),s=[],n=(r,i,o)=>{if(!(o>3)&&!(s.length>50))try{let c=Me.readdirSync(r,{withFileTypes:!0}).filter(u=>!u.name.startsWith(".")&&!t.has(u.name));for(let u=0;u<c.length&&s.length<50;u++){let d=c[u],p=u===c.length-1,h=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",g=p?" ":"\u2502 ";d.isDirectory()?(s.push(`${i}${h}${d.name}/`),n(te.join(r,d.name),i+g,o+1)):s.push(`${i}${h}${d.name}`);}}catch{}};return s.push(te.basename(this.config.workDir)+"/"),n(this.config.workDir,"",1),s.join(`
2442
2442
  `)}findKeyFiles(){let e=[],t=["package.json","tsconfig.json","README.md","src/index.ts","src/main.ts","src/app.ts","src/App.tsx","src/pages/index.tsx","src/routes/index.ts","prisma/schema.prisma","docker-compose.yml","Dockerfile"];for(let s of t){let n=te.join(this.config.workDir,s);Me.existsSync(n)&&e.push(s);}return e}getPackageDependencies(){try{let e=te.join(this.config.workDir,"package.json");if(!Me.existsSync(e))return;let t=JSON.parse(Me.readFileSync(e,"utf-8")),s=Object.keys(t.dependencies||{}).slice(0,15),n=Object.keys(t.devDependencies||{}).slice(0,10),r="";return s.length>0&&(r+=`Dependencies: ${s.join(", ")}`,Object.keys(t.dependencies||{}).length>15&&(r+=` (+${Object.keys(t.dependencies||{}).length-15} more)`)),n.length>0&&(r+=`
@@ -2596,7 +2596,7 @@ ${a.codebaseContext}
2596
2596
  "maxParallelism": 1,
2597
2597
  "estimatedTotalTime": 60
2598
2598
  }
2599
- }`;var Do=class{validate(e,t){let s=[],n=[];if(e.size===0)return s.push("DAG \u6CA1\u6709\u4EFB\u4F55\u8282\u70B9"),{valid:false,errors:s,warnings:n};let r=this.detectCycles(e);r&&s.push(r);let i=this.validateDependencies(e);s.push(...i);let o=this.validateLevels(e,t);s.push(...o);let l=this.validateRoots(e,t);s.push(...l);let c=this.validateLeaves(e,t);s.push(...c);let u=this.validateTasks(e);n.push(...u);let d=this.validateIOMapping(e);return n.push(...d),{valid:s.length===0,errors:s,warnings:n}}detectCycles(e){let t=new Set,s=new Set,n=(r,i)=>{if(s.has(r)){let l=i.indexOf(r);return `\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56: ${[...i.slice(l),r].join(" -> ")}`}if(t.has(r))return null;t.add(r),s.add(r);let o=e.get(r);if(o)for(let l of o.dependencies){let c=n(l,[...i,r]);if(c)return c}return s.delete(r),null};for(let r of e.keys()){let i=n(r,[]);if(i)return i}return null}validateDependencies(e){let t=[];for(let[s,n]of e){for(let r of n.dependencies)e.has(r)||t.push(`\u8282\u70B9 ${s} \u4F9D\u8D56\u4E0D\u5B58\u5728\u7684\u8282\u70B9: ${r}`);for(let r of n.dependents)e.has(r)||t.push(`\u8282\u70B9 ${s} \u7684\u88AB\u4F9D\u8D56\u8282\u70B9\u4E0D\u5B58\u5728: ${r}`);}return t}validateLevels(e,t){let s=[],n=new Set(t.levels.flat());for(let i of e.keys())n.has(i)||s.push(`\u8282\u70B9 ${i} \u6CA1\u6709\u88AB\u5206\u914D\u5230\u4EFB\u4F55\u5C42\u7EA7`);for(let i of t.levels)for(let o of i)e.has(o)||s.push(`\u5C42\u7EA7\u4E2D\u5305\u542B\u4E0D\u5B58\u5728\u7684\u8282\u70B9: ${o}`);let r=new Map;for(let i=0;i<t.levels.length;i++)for(let o of t.levels[i])r.set(o,i);for(let[i,o]of e){let l=r.get(i)??-1;for(let c of o.dependencies){let u=r.get(c)??-1;u>=l&&s.push(`\u8282\u70B9 ${i} (\u5C42\u7EA7 ${l}) \u4F9D\u8D56\u4E86\u540C\u5C42\u6216\u66F4\u665A\u5C42\u7EA7\u7684\u8282\u70B9 ${c} (\u5C42\u7EA7 ${u})`);}}return s}validateRoots(e,t){let s=[];for(let n of t.roots){let r=e.get(n);if(!r){s.push(`\u6839\u8282\u70B9\u4E0D\u5B58\u5728: ${n}`);continue}r.dependencies.length>0&&s.push(`\u6839\u8282\u70B9 ${n} \u4E0D\u5E94\u8BE5\u6709\u4F9D\u8D56: ${r.dependencies.join(", ")}`);}for(let[n,r]of e)r.dependencies.length===0&&!t.roots.includes(n)&&s.push(`\u8282\u70B9 ${n} \u6CA1\u6709\u4F9D\u8D56\uFF0C\u4F46\u672A\u88AB\u6807\u8BB0\u4E3A\u6839\u8282\u70B9`);return s}validateLeaves(e,t){let s=[];for(let n of t.leaves){let r=e.get(n);if(!r){s.push(`\u53F6\u8282\u70B9\u4E0D\u5B58\u5728: ${n}`);continue}r.dependents.length>0&&s.push(`\u53F6\u8282\u70B9 ${n} \u4E0D\u5E94\u8BE5\u88AB\u4F9D\u8D56: ${r.dependents.join(", ")}`);}return s}validateTasks(e){let t=[];for(let[s,n]of e)(!n.task.description||n.task.description.length<10)&&t.push(`\u8282\u70B9 ${s} \u7684\u4EFB\u52A1\u63CF\u8FF0\u8FC7\u77ED\uFF0C\u53EF\u80FD\u4E0D\u591F\u8BE6\u7EC6`),n.task.role||t.push(`\u8282\u70B9 ${s} \u6CA1\u6709\u5206\u914D\u89D2\u8272`),n.execution.estimatedDuration<=0&&t.push(`\u8282\u70B9 ${s} \u7684\u9884\u4F30\u8017\u65F6\u65E0\u6548`),n.execution.estimatedTokens<=0&&t.push(`\u8282\u70B9 ${s} \u7684\u9884\u4F30 Token \u65E0\u6548`);return t}validateIOMapping(e){let t=[],s=new Set;for(let n of e.values())n.io.outputKey&&(s.has(n.io.outputKey)&&t.push(`\u8F93\u51FA key \u91CD\u590D: ${n.io.outputKey}`),s.add(n.io.outputKey));for(let[n,r]of e)for(let[i,o]of Object.entries(r.io.inputMapping)){let l=o.match(/\{\{(.+)\}\}/);if(l){let c=l[1];if(c==="user_request")continue;!s.has(c)&&!c.endsWith("_output")&&t.push(`\u8282\u70B9 ${n} \u7684\u8F93\u5165 ${i} \u5F15\u7528\u4E86\u53EF\u80FD\u4E0D\u5B58\u5728\u7684 key: ${c}`);}}return t}};function cc(){return new Do}var yC={maxParallelism:5,maxTokensPerTask:5e3,optimizeParallelism:true},Lo=class{llmCall;config;onEvent;validator;constructor(e){this.llmCall=e.llmCall,this.config={...yC,...e.config},this.onEvent=e.onEvent,this.validator=cc();}async plan(e){let t=this.generateDAGId();this.emitEvent({type:"dag_planning_start",timestamp:Date.now(),data:{dagId:t}});try{let s=ac(e),n=await this.llmCall(oc,s),{nodes:r,analysis:i}=this.parseResponse(n),o=this.validator.validate(r,i);if(this.emitEvent({type:"dag_validation_complete",timestamp:Date.now(),data:{dagId:t,result:o}}),!o.valid){console.warn("[DAGPlanner] Validation failed:",o.errors);let c=this.attemptFix(r,i,o.errors);if(c){r.clear();for(let[u,d]of c)r.set(u,d);}}this.config.optimizeParallelism&&this.optimizeParallelism(r,i);let l={id:t,nodes:r,analysis:i,state:{phase:"planning",currentLevel:0,completedNodes:[],failedNodes:[]}};return this.emitEvent({type:"dag_planning_complete",timestamp:Date.now(),data:{dagId:t,result:{nodeCount:r.size,levels:i.levels.length,maxParallelism:i.maxParallelism,estimatedTime:i.estimatedTotalTime}}}),l}catch(s){return console.error("[DAGPlanner] Planning failed:",s),this.createFallbackDAG(t,e.userRequest)}}async planSimple(e){let t=this.generateDAGId();this.emitEvent({type:"dag_planning_start",timestamp:Date.now(),data:{dagId:t}});try{let s=await this.llmCall(lc,e),{nodes:n,analysis:r}=this.parseResponse(s),i={id:t,nodes:n,analysis:r,state:{phase:"planning",currentLevel:0,completedNodes:[],failedNodes:[]}};return this.emitEvent({type:"dag_planning_complete",timestamp:Date.now(),data:{dagId:t}}),i}catch{return this.createFallbackDAG(t,e)}}parseResponse(e){let t=e.match(/\{[\s\S]*\}/);if(!t)throw new Error("No JSON found in response");let s=JSON.parse(t[0]);if(!s.nodes||!Array.isArray(s.nodes))throw new Error("Invalid nodes in response");if(!s.analysis)throw new Error("Invalid analysis in response");let n=new Map;for(let i of s.nodes){let o={id:i.id,task:{description:i.task?.description||"",role:i.task?.role||"executor",requiredCapabilities:i.task?.requiredCapabilities||[]},dependencies:i.dependencies||[],dependents:[],execution:{estimatedDuration:i.execution?.estimatedDuration||60,estimatedTokens:i.execution?.estimatedTokens||2e3,priority:i.execution?.priority||5,parallelGroup:i.execution?.parallelGroup},io:{inputMapping:i.io?.inputMapping||{},outputKey:i.io?.outputKey||`${i.id}_output`},status:"pending"};n.set(o.id,o);}for(let[i,o]of n)for(let l of o.dependencies){let c=n.get(l);c&&c.dependents.push(i);}let r={roots:s.analysis.roots||[],leaves:s.analysis.leaves||[],levels:s.analysis.levels||[],criticalPath:s.analysis.criticalPath||[],maxParallelism:s.analysis.maxParallelism||1,estimatedTotalTime:s.analysis.estimatedTotalTime||60};return {nodes:n,analysis:r}}attemptFix(e,t,s){let n={...t};n.roots=[];for(let[r,i]of e)i.dependencies.length===0&&n.roots.push(r);n.leaves=[];for(let[r,i]of e)i.dependents.length===0&&n.leaves.push(r);return s.some(r=>r.includes("\u5C42\u7EA7"))&&(n.levels=this.computeLevels(e)),t.roots=n.roots,t.leaves=n.leaves,t.levels=n.levels,e}computeLevels(e){let t=[],s=new Set;for(;s.size<e.size;){let n=[];for(let[r,i]of e){if(s.has(r))continue;i.dependencies.every(l=>s.has(l))&&n.push(r);}if(n.length===0){console.error("[DAGPlanner] Unable to compute levels, possible cycle");break}t.push(n);for(let r of n)s.add(r);}return t}optimizeParallelism(e,t){let s=this.config.maxParallelism??5;for(let n=0;n<t.levels.length;n++){let r=t.levels[n];if(r.length>s){let i=[];for(let o=0;o<r.length;o+=s)i.push(r.slice(o,o+s));console.log(`[DAGPlanner] Level ${n} has ${r.length} nodes, max is ${s}`);}}t.maxParallelism=Math.min(Math.max(...t.levels.map(n=>n.length)),s);}createFallbackDAG(e,t){let s="fallback-node",n={id:s,task:{description:`\u6267\u884C\u7528\u6237\u8BF7\u6C42: ${t.substring(0,100)}`,role:"executor",requiredCapabilities:["general"]},dependencies:[],dependents:[],execution:{estimatedDuration:120,estimatedTokens:3e3,priority:5},io:{inputMapping:{request:"{{user_request}}"},outputKey:"result"},status:"pending"},r=new Map;return r.set(s,n),{id:e,nodes:r,analysis:{roots:[s],leaves:[s],levels:[[s]],criticalPath:[s],maxParallelism:1,estimatedTotalTime:120},state:{phase:"planning",currentLevel:0,completedNodes:[],failedNodes:[]}}}generateDAGId(){return `dag-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}emitEvent(e){this.onEvent&&this.onEvent(e);}updateConfig(e){this.config={...this.config,...e};}};function uc(a){return new Lo(a)}var Oo=class{instances=new Map;llmCall;onEvent;defaultTimeout;constructor(e){this.llmCall=e.llmCall,this.onEvent=e.onEvent,this.defaultTimeout=e.defaultTimeout??3e5;}createInstance(e){let t={id:this.generateInstanceId(),nodeId:e.id,role:e.task.role,status:"idle",createdAt:Date.now()};return this.instances.set(t.id,t),t}async execute(e,t,s){let n=s?.timeout??this.defaultTimeout,r=Date.now();e.status="busy",e.startedAt=r,this.instances.set(e.id,e);try{let i=await this.executeWithTimeout(this.llmCall(t.systemPrompt,t.userPrompt,{model:s?.model,onText:s?.onText,nodeId:e.nodeId,onRuntimeEvent:s?.onRuntimeEvent,previousToolCalls:s?.previousToolCalls}),n),o=Date.now(),l=o-r,c={output:i,tokenUsage:{input:t.estimatedTokens,output:Math.ceil(i.length/2.5),total:t.estimatedTokens+Math.ceil(i.length/2.5)},duration:l};return e.status="completed",e.completedAt=o,e.result=c,this.instances.set(e.id,e),c}catch(i){let o=Date.now(),l=i instanceof Error?i.message:String(i);throw e.status="failed",e.completedAt=o,e.error=l,this.instances.set(e.id,e),i}}async executeWithTimeout(e,t){return Promise.race([e,new Promise((s,n)=>{setTimeout(()=>{n(new Error(`\u6267\u884C\u8D85\u65F6 (${t}ms)`));},t);})])}getInstance(e){return this.instances.get(e)}getInstanceByNodeId(e){for(let t of this.instances.values())if(t.nodeId===e)return t}getAllInstances(){return Array.from(this.instances.values())}getInstancesByStatus(e){return Array.from(this.instances.values()).filter(t=>t.status===e)}terminate(e){let t=this.instances.get(e);return t?(t.status="terminated",t.completedAt=Date.now(),this.instances.set(e,t),true):false}cleanup(){let e=0;for(let[t,s]of this.instances)(s.status==="completed"||s.status==="failed"||s.status==="terminated")&&(this.instances.delete(t),e++);return e}reset(){this.instances.clear();}getStats(){let e={total:this.instances.size,idle:0,busy:0,completed:0,failed:0,terminated:0};for(let t of this.instances.values())switch(t.status){case "idle":e.idle++;break;case "busy":e.busy++;break;case "completed":e.completed++;break;case "failed":e.failed++;break;case "terminated":e.terminated++;break}return e}generateInstanceId(){return `agent-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}emitEvent(e){this.onEvent&&this.onEvent(e);}};function dc(a){return new Oo(a)}var No=class{context;constructor(e,t){this.context={dagId:e,userRequest:t,entries:new Map,metadata:{}},this.set("user_request",t,"system");}set(e,t,s){let n=this.context.entries.get(e),r=n?n.version+1:1,i={key:e,value:t,sourceNodeId:s,createdAt:Date.now(),version:r};this.context.entries.set(e,i);}get(e){return this.context.entries.get(e)?.value}getEntry(e){return this.context.entries.get(e)}has(e){return this.context.entries.has(e)}resolveInputMapping(e){let t={};for(let[s,n]of Object.entries(e)){let r=n.match(/\{\{(.+)\}\}/);if(r){let i=r[1],o=this.get(i);if(o!==void 0)t[s]=o;else if(i.match(/(.+)_output$/)){let c=this.get(i);t[s]=c??`[\u672A\u627E\u5230: ${i}]`;}else t[s]=`[\u672A\u627E\u5230: ${i}]`;}else t[s]=n;}return t}storeNodeOutput(e,t,s){this.set(t,s,e);let n=`${e}_output`;t!==n&&this.set(n,s,e);}setMetadata(e,t){this.context.metadata[e]=t;}getMetadata(e){return this.context.metadata[e]}getAllEntries(){return new Map(this.context.entries)}getSummary(){let e=Array.from(this.context.entries.entries());if(e.length===0)return "\u65E0\u53EF\u7528\u4E0A\u4E0B\u6587";let t=[];for(let[s,n]of e){if(s==="user_request")continue;let r=typeof n.value=="string"?n.value.substring(0,100)+(n.value.length>100?"...":""):JSON.stringify(n.value).substring(0,100);t.push(`- ${s}: ${r}`);}return t.join(`
2599
+ }`;var Do=class{validate(e,t){let s=[],n=[];if(e.size===0)return s.push("DAG \u6CA1\u6709\u4EFB\u4F55\u8282\u70B9"),{valid:false,errors:s,warnings:n};let r=this.detectCycles(e);r&&s.push(r);let i=this.validateDependencies(e);s.push(...i);let o=this.validateLevels(e,t);s.push(...o);let l=this.validateRoots(e,t);s.push(...l);let c=this.validateLeaves(e,t);s.push(...c);let u=this.validateTasks(e);n.push(...u);let d=this.validateIOMapping(e);return n.push(...d),{valid:s.length===0,errors:s,warnings:n}}detectCycles(e){let t=new Set,s=new Set,n=(r,i)=>{if(s.has(r)){let l=i.indexOf(r);return `\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56: ${[...i.slice(l),r].join(" -> ")}`}if(t.has(r))return null;t.add(r),s.add(r);let o=e.get(r);if(o)for(let l of o.dependencies){let c=n(l,[...i,r]);if(c)return c}return s.delete(r),null};for(let r of e.keys()){let i=n(r,[]);if(i)return i}return null}validateDependencies(e){let t=[];for(let[s,n]of e){for(let r of n.dependencies)e.has(r)||t.push(`\u8282\u70B9 ${s} \u4F9D\u8D56\u4E0D\u5B58\u5728\u7684\u8282\u70B9: ${r}`);for(let r of n.dependents)e.has(r)||t.push(`\u8282\u70B9 ${s} \u7684\u88AB\u4F9D\u8D56\u8282\u70B9\u4E0D\u5B58\u5728: ${r}`);}return t}validateLevels(e,t){let s=[],n=new Set(t.levels.flat());for(let i of e.keys())n.has(i)||s.push(`\u8282\u70B9 ${i} \u6CA1\u6709\u88AB\u5206\u914D\u5230\u4EFB\u4F55\u5C42\u7EA7`);for(let i of t.levels)for(let o of i)e.has(o)||s.push(`\u5C42\u7EA7\u4E2D\u5305\u542B\u4E0D\u5B58\u5728\u7684\u8282\u70B9: ${o}`);let r=new Map;for(let i=0;i<t.levels.length;i++)for(let o of t.levels[i])r.set(o,i);for(let[i,o]of e){let l=r.get(i)??-1;for(let c of o.dependencies){let u=r.get(c)??-1;u>=l&&s.push(`\u8282\u70B9 ${i} (\u5C42\u7EA7 ${l}) \u4F9D\u8D56\u4E86\u540C\u5C42\u6216\u66F4\u665A\u5C42\u7EA7\u7684\u8282\u70B9 ${c} (\u5C42\u7EA7 ${u})`);}}return s}validateRoots(e,t){let s=[];for(let n of t.roots){let r=e.get(n);if(!r){s.push(`\u6839\u8282\u70B9\u4E0D\u5B58\u5728: ${n}`);continue}r.dependencies.length>0&&s.push(`\u6839\u8282\u70B9 ${n} \u4E0D\u5E94\u8BE5\u6709\u4F9D\u8D56: ${r.dependencies.join(", ")}`);}for(let[n,r]of e)r.dependencies.length===0&&!t.roots.includes(n)&&s.push(`\u8282\u70B9 ${n} \u6CA1\u6709\u4F9D\u8D56\uFF0C\u4F46\u672A\u88AB\u6807\u8BB0\u4E3A\u6839\u8282\u70B9`);return s}validateLeaves(e,t){let s=[];for(let n of t.leaves){let r=e.get(n);if(!r){s.push(`\u53F6\u8282\u70B9\u4E0D\u5B58\u5728: ${n}`);continue}r.dependents.length>0&&s.push(`\u53F6\u8282\u70B9 ${n} \u4E0D\u5E94\u8BE5\u88AB\u4F9D\u8D56: ${r.dependents.join(", ")}`);}return s}validateTasks(e){let t=[];for(let[s,n]of e)(!n.task.description||n.task.description.length<10)&&t.push(`\u8282\u70B9 ${s} \u7684\u4EFB\u52A1\u63CF\u8FF0\u8FC7\u77ED\uFF0C\u53EF\u80FD\u4E0D\u591F\u8BE6\u7EC6`),n.task.role||t.push(`\u8282\u70B9 ${s} \u6CA1\u6709\u5206\u914D\u89D2\u8272`),n.execution.estimatedDuration<=0&&t.push(`\u8282\u70B9 ${s} \u7684\u9884\u4F30\u8017\u65F6\u65E0\u6548`),n.execution.estimatedTokens<=0&&t.push(`\u8282\u70B9 ${s} \u7684\u9884\u4F30 Token \u65E0\u6548`);return t}validateIOMapping(e){let t=[],s=new Set;for(let n of e.values())n.io.outputKey&&(s.has(n.io.outputKey)&&t.push(`\u8F93\u51FA key \u91CD\u590D: ${n.io.outputKey}`),s.add(n.io.outputKey));for(let[n,r]of e)for(let[i,o]of Object.entries(r.io.inputMapping)){let l=o.match(/\{\{(.+)\}\}/);if(l){let c=l[1];if(c==="user_request")continue;!s.has(c)&&!c.endsWith("_output")&&t.push(`\u8282\u70B9 ${n} \u7684\u8F93\u5165 ${i} \u5F15\u7528\u4E86\u53EF\u80FD\u4E0D\u5B58\u5728\u7684 key: ${c}`);}}return t}};function cc(){return new Do}var bC={maxParallelism:5,maxTokensPerTask:5e3,optimizeParallelism:true},Lo=class{llmCall;config;onEvent;validator;constructor(e){this.llmCall=e.llmCall,this.config={...bC,...e.config},this.onEvent=e.onEvent,this.validator=cc();}async plan(e){let t=this.generateDAGId();this.emitEvent({type:"dag_planning_start",timestamp:Date.now(),data:{dagId:t}});try{let s=ac(e),n=await this.llmCall(oc,s),{nodes:r,analysis:i}=this.parseResponse(n),o=this.validator.validate(r,i);if(this.emitEvent({type:"dag_validation_complete",timestamp:Date.now(),data:{dagId:t,result:o}}),!o.valid){console.warn("[DAGPlanner] Validation failed:",o.errors);let c=this.attemptFix(r,i,o.errors);if(c){r.clear();for(let[u,d]of c)r.set(u,d);}}this.config.optimizeParallelism&&this.optimizeParallelism(r,i);let l={id:t,nodes:r,analysis:i,state:{phase:"planning",currentLevel:0,completedNodes:[],failedNodes:[]}};return this.emitEvent({type:"dag_planning_complete",timestamp:Date.now(),data:{dagId:t,result:{nodeCount:r.size,levels:i.levels.length,maxParallelism:i.maxParallelism,estimatedTime:i.estimatedTotalTime}}}),l}catch(s){return console.error("[DAGPlanner] Planning failed:",s),this.createFallbackDAG(t,e.userRequest)}}async planSimple(e){let t=this.generateDAGId();this.emitEvent({type:"dag_planning_start",timestamp:Date.now(),data:{dagId:t}});try{let s=await this.llmCall(lc,e),{nodes:n,analysis:r}=this.parseResponse(s),i={id:t,nodes:n,analysis:r,state:{phase:"planning",currentLevel:0,completedNodes:[],failedNodes:[]}};return this.emitEvent({type:"dag_planning_complete",timestamp:Date.now(),data:{dagId:t}}),i}catch{return this.createFallbackDAG(t,e)}}parseResponse(e){let t=e.match(/\{[\s\S]*\}/);if(!t)throw new Error("No JSON found in response");let s=JSON.parse(t[0]);if(!s.nodes||!Array.isArray(s.nodes))throw new Error("Invalid nodes in response");if(!s.analysis)throw new Error("Invalid analysis in response");let n=new Map;for(let i of s.nodes){let o={id:i.id,task:{description:i.task?.description||"",role:i.task?.role||"executor",requiredCapabilities:i.task?.requiredCapabilities||[]},dependencies:i.dependencies||[],dependents:[],execution:{estimatedDuration:i.execution?.estimatedDuration||60,estimatedTokens:i.execution?.estimatedTokens||2e3,priority:i.execution?.priority||5,parallelGroup:i.execution?.parallelGroup},io:{inputMapping:i.io?.inputMapping||{},outputKey:i.io?.outputKey||`${i.id}_output`},status:"pending"};n.set(o.id,o);}for(let[i,o]of n)for(let l of o.dependencies){let c=n.get(l);c&&c.dependents.push(i);}let r={roots:s.analysis.roots||[],leaves:s.analysis.leaves||[],levels:s.analysis.levels||[],criticalPath:s.analysis.criticalPath||[],maxParallelism:s.analysis.maxParallelism||1,estimatedTotalTime:s.analysis.estimatedTotalTime||60};return {nodes:n,analysis:r}}attemptFix(e,t,s){let n={...t};n.roots=[];for(let[r,i]of e)i.dependencies.length===0&&n.roots.push(r);n.leaves=[];for(let[r,i]of e)i.dependents.length===0&&n.leaves.push(r);return s.some(r=>r.includes("\u5C42\u7EA7"))&&(n.levels=this.computeLevels(e)),t.roots=n.roots,t.leaves=n.leaves,t.levels=n.levels,e}computeLevels(e){let t=[],s=new Set;for(;s.size<e.size;){let n=[];for(let[r,i]of e){if(s.has(r))continue;i.dependencies.every(l=>s.has(l))&&n.push(r);}if(n.length===0){console.error("[DAGPlanner] Unable to compute levels, possible cycle");break}t.push(n);for(let r of n)s.add(r);}return t}optimizeParallelism(e,t){let s=this.config.maxParallelism??5;for(let n=0;n<t.levels.length;n++){let r=t.levels[n];if(r.length>s){let i=[];for(let o=0;o<r.length;o+=s)i.push(r.slice(o,o+s));console.log(`[DAGPlanner] Level ${n} has ${r.length} nodes, max is ${s}`);}}t.maxParallelism=Math.min(Math.max(...t.levels.map(n=>n.length)),s);}createFallbackDAG(e,t){let s="fallback-node",n={id:s,task:{description:`\u6267\u884C\u7528\u6237\u8BF7\u6C42: ${t.substring(0,100)}`,role:"executor",requiredCapabilities:["general"]},dependencies:[],dependents:[],execution:{estimatedDuration:120,estimatedTokens:3e3,priority:5},io:{inputMapping:{request:"{{user_request}}"},outputKey:"result"},status:"pending"},r=new Map;return r.set(s,n),{id:e,nodes:r,analysis:{roots:[s],leaves:[s],levels:[[s]],criticalPath:[s],maxParallelism:1,estimatedTotalTime:120},state:{phase:"planning",currentLevel:0,completedNodes:[],failedNodes:[]}}}generateDAGId(){return `dag-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}emitEvent(e){this.onEvent&&this.onEvent(e);}updateConfig(e){this.config={...this.config,...e};}};function uc(a){return new Lo(a)}var Oo=class{instances=new Map;llmCall;onEvent;defaultTimeout;constructor(e){this.llmCall=e.llmCall,this.onEvent=e.onEvent,this.defaultTimeout=e.defaultTimeout??3e5;}createInstance(e){let t={id:this.generateInstanceId(),nodeId:e.id,role:e.task.role,status:"idle",createdAt:Date.now()};return this.instances.set(t.id,t),t}async execute(e,t,s){let n=s?.timeout??this.defaultTimeout,r=Date.now();e.status="busy",e.startedAt=r,this.instances.set(e.id,e);try{let i=await this.executeWithTimeout(this.llmCall(t.systemPrompt,t.userPrompt,{model:s?.model,onText:s?.onText,nodeId:e.nodeId,onRuntimeEvent:s?.onRuntimeEvent,previousToolCalls:s?.previousToolCalls}),n),o=Date.now(),l=o-r,c={output:i,tokenUsage:{input:t.estimatedTokens,output:Math.ceil(i.length/2.5),total:t.estimatedTokens+Math.ceil(i.length/2.5)},duration:l};return e.status="completed",e.completedAt=o,e.result=c,this.instances.set(e.id,e),c}catch(i){let o=Date.now(),l=i instanceof Error?i.message:String(i);throw e.status="failed",e.completedAt=o,e.error=l,this.instances.set(e.id,e),i}}async executeWithTimeout(e,t){return Promise.race([e,new Promise((s,n)=>{setTimeout(()=>{n(new Error(`\u6267\u884C\u8D85\u65F6 (${t}ms)`));},t);})])}getInstance(e){return this.instances.get(e)}getInstanceByNodeId(e){for(let t of this.instances.values())if(t.nodeId===e)return t}getAllInstances(){return Array.from(this.instances.values())}getInstancesByStatus(e){return Array.from(this.instances.values()).filter(t=>t.status===e)}terminate(e){let t=this.instances.get(e);return t?(t.status="terminated",t.completedAt=Date.now(),this.instances.set(e,t),true):false}cleanup(){let e=0;for(let[t,s]of this.instances)(s.status==="completed"||s.status==="failed"||s.status==="terminated")&&(this.instances.delete(t),e++);return e}reset(){this.instances.clear();}getStats(){let e={total:this.instances.size,idle:0,busy:0,completed:0,failed:0,terminated:0};for(let t of this.instances.values())switch(t.status){case "idle":e.idle++;break;case "busy":e.busy++;break;case "completed":e.completed++;break;case "failed":e.failed++;break;case "terminated":e.terminated++;break}return e}generateInstanceId(){return `agent-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}emitEvent(e){this.onEvent&&this.onEvent(e);}};function dc(a){return new Oo(a)}var No=class{context;constructor(e,t){this.context={dagId:e,userRequest:t,entries:new Map,metadata:{}},this.set("user_request",t,"system");}set(e,t,s){let n=this.context.entries.get(e),r=n?n.version+1:1,i={key:e,value:t,sourceNodeId:s,createdAt:Date.now(),version:r};this.context.entries.set(e,i);}get(e){return this.context.entries.get(e)?.value}getEntry(e){return this.context.entries.get(e)}has(e){return this.context.entries.has(e)}resolveInputMapping(e){let t={};for(let[s,n]of Object.entries(e)){let r=n.match(/\{\{(.+)\}\}/);if(r){let i=r[1],o=this.get(i);if(o!==void 0)t[s]=o;else if(i.match(/(.+)_output$/)){let c=this.get(i);t[s]=c??`[\u672A\u627E\u5230: ${i}]`;}else t[s]=`[\u672A\u627E\u5230: ${i}]`;}else t[s]=n;}return t}storeNodeOutput(e,t,s){this.set(t,s,e);let n=`${e}_output`;t!==n&&this.set(n,s,e);}setMetadata(e,t){this.context.metadata[e]=t;}getMetadata(e){return this.context.metadata[e]}getAllEntries(){return new Map(this.context.entries)}getSummary(){let e=Array.from(this.context.entries.entries());if(e.length===0)return "\u65E0\u53EF\u7528\u4E0A\u4E0B\u6587";let t=[];for(let[s,n]of e){if(s==="user_request")continue;let r=typeof n.value=="string"?n.value.substring(0,100)+(n.value.length>100?"...":""):JSON.stringify(n.value).substring(0,100);t.push(`- ${s}: ${r}`);}return t.join(`
2600
2600
  `)}getUserRequest(){return this.context.userRequest}getDAGId(){return this.context.dagId}clear(){this.context.entries.clear(),this.context.metadata={},this.set("user_request",this.context.userRequest,"system");}export(){let e={};for(let[t,s]of this.context.entries)e[t]={value:s.value,source:s.sourceNodeId,version:s.version};return {dagId:this.context.dagId,userRequest:this.context.userRequest,entries:e,metadata:this.context.metadata}}};function pc(a,e){return new No(a,e)}var Er={executor:`\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u6267\u884C\u4E13\u5BB6\u3002\u4F60\u7684\u804C\u8D23\u662F\u51C6\u786E\u3001\u9AD8\u6548\u5730\u5B8C\u6210\u5206\u914D\u7ED9\u4F60\u7684\u4EFB\u52A1\u3002
2601
2601
 
2602
2602
  ## \u6267\u884C\u539F\u5219
@@ -2656,13 +2656,13 @@ ${r}
2656
2656
  `;}return e.contextSummary&&(t+=`## \u76F8\u5173\u4E0A\u4E0B\u6587
2657
2657
  ${e.contextSummary}
2658
2658
 
2659
- `),t+="\u8BF7\u6839\u636E\u4EE5\u4E0A\u4FE1\u606F\u6267\u884C\u4EFB\u52A1\uFF0C\u5E76\u8F93\u51FA\u7ED3\u679C\u3002",t}estimateTokens(e,t){let s=e.length+t.length;return Math.ceil(s/2.5)}getRolePrompt(e){return Er[e]||Er.general}registerRolePrompt(e,t){Er[e]=t;}};function mc(){return new $o}W();var bC={edit_file:"file_edit",edit:"file_edit",str_replace_editor:"file_edit",write_file:"file_write",write:"file_write",create_file:"file_write",read_file:"file_read",read:"file_read",view_file:"file_read",bash:"command",execute_command:"command",run_terminal_command:"command",shell:"command",grep:"search",glob:"search",search:"search",find_files:"search",list_files:"search",web_search:"web",web_fetch:"web",browser:"web"},Fo=class{snapshots=new Map;maxActionsPerNode=20;maxSummaryLength=200;maxToolResultLength=2e3;getOrCreateSnapshot(e){let t=this.snapshots.get(e);return t||(t={nodeId:e,toolCallMessages:[],completedActions:[],partialOutput:"",createdAt:Date.now(),updatedAt:Date.now(),retryCount:0},this.snapshots.set(e,t)),t}getSnapshot(e){return this.snapshots.get(e)}recordToolCall(e,t,s,n,r,i){let o=this.getOrCreateSnapshot(e),l={toolId:i||`tool-${Date.now()}-${Math.random().toString(36).substring(2,6)}`,toolName:t,args:s,result:n.length>this.maxToolResultLength?n.substring(0,this.maxToolResultLength)+`
2660
- ...[truncated]`:n,success:r,timestamp:Date.now()};o.toolCallMessages.push(l);let c=bC[t.toLowerCase()]||"other",u=this.extractTarget(t,s),d=this.generateSummary(t,s,n,r),p={type:c,toolName:t,target:u,summary:d,success:r,timestamp:Date.now()};o.completedActions.push(p),o.completedActions.length>this.maxActionsPerNode&&(o.completedActions.shift(),o.toolCallMessages.shift()),o.updatedAt=Date.now(),m.debug("NODE_CONTEXT",`Recorded action for ${e}`,{type:c,toolName:t,target:u,success:r,totalActions:o.completedActions.length,totalToolMessages:o.toolCallMessages.length});}getToolCallMessages(e){let t=this.getSnapshot(e);return t?t.toolCallMessages:[]}hasToolCallHistory(e){let t=this.getSnapshot(e);return t!==void 0&&t.toolCallMessages.length>0}appendPartialOutput(e,t){let s=this.getOrCreateSnapshot(e);s.partialOutput+=t,s.updatedAt=Date.now(),s.partialOutput.length>5e3&&(s.partialOutput=s.partialOutput.slice(-5e3));}incrementRetryCount(e){let t=this.getOrCreateSnapshot(e);return t.retryCount++,t.updatedAt=Date.now(),t.retryCount}buildResumePrompt(e){let t=this.getSnapshot(e);if(!t||t.completedActions.length===0)return null;let s=["\u3010\u91CD\u8981\u63D0\u793A\u3011\u8FD9\u662F\u4E00\u4E2A\u91CD\u8BD5\u8BF7\u6C42\u3002\u5728\u4E4B\u524D\u7684\u5C1D\u8BD5\u4E2D\uFF0C\u4EE5\u4E0B\u64CD\u4F5C\u5DF2\u7ECF\u6210\u529F\u5B8C\u6210\uFF1A",""],n=this.groupActionsByType(t.completedActions);for(let[r,i]of Object.entries(n)){if(i.length===0)continue;let o=this.getTypeLabel(r);s.push(`## ${o} (${i.length} \u9879\u5DF2\u5B8C\u6210)`);for(let l of i){let c=l.success?"\u2713":"\u2717";s.push(`- ${c} ${l.target}: ${l.summary}`);}s.push("");}return s.push("\u8BF7\u4ECE\u4E0A\u6B21\u4E2D\u65AD\u7684\u5730\u65B9\u7EE7\u7EED\uFF0C\u4E0D\u8981\u91CD\u590D\u6267\u884C\u5DF2\u5B8C\u6210\u7684\u64CD\u4F5C\u3002"),s.push("\u5982\u679C\u67D0\u4E2A\u6587\u4EF6\u5DF2\u7ECF\u88AB\u7F16\u8F91\u8FC7\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u72B6\u6001\u800C\u4E0D\u662F\u518D\u6B21\u7F16\u8F91\u3002"),s.push(""),s.join(`
2659
+ `),t+="\u8BF7\u6839\u636E\u4EE5\u4E0A\u4FE1\u606F\u6267\u884C\u4EFB\u52A1\uFF0C\u5E76\u8F93\u51FA\u7ED3\u679C\u3002",t}estimateTokens(e,t){let s=e.length+t.length;return Math.ceil(s/2.5)}getRolePrompt(e){return Er[e]||Er.general}registerRolePrompt(e,t){Er[e]=t;}};function mc(){return new $o}W();var vC={edit_file:"file_edit",edit:"file_edit",str_replace_editor:"file_edit",write_file:"file_write",write:"file_write",create_file:"file_write",read_file:"file_read",read:"file_read",view_file:"file_read",bash:"command",execute_command:"command",run_terminal_command:"command",shell:"command",grep:"search",glob:"search",search:"search",find_files:"search",list_files:"search",web_search:"web",web_fetch:"web",browser:"web"},Fo=class{snapshots=new Map;maxActionsPerNode=20;maxSummaryLength=200;maxToolResultLength=2e3;getOrCreateSnapshot(e){let t=this.snapshots.get(e);return t||(t={nodeId:e,toolCallMessages:[],completedActions:[],partialOutput:"",createdAt:Date.now(),updatedAt:Date.now(),retryCount:0},this.snapshots.set(e,t)),t}getSnapshot(e){return this.snapshots.get(e)}recordToolCall(e,t,s,n,r,i){let o=this.getOrCreateSnapshot(e),l={toolId:i||`tool-${Date.now()}-${Math.random().toString(36).substring(2,6)}`,toolName:t,args:s,result:n.length>this.maxToolResultLength?n.substring(0,this.maxToolResultLength)+`
2660
+ ...[truncated]`:n,success:r,timestamp:Date.now()};o.toolCallMessages.push(l);let c=vC[t.toLowerCase()]||"other",u=this.extractTarget(t,s),d=this.generateSummary(t,s,n,r),p={type:c,toolName:t,target:u,summary:d,success:r,timestamp:Date.now()};o.completedActions.push(p),o.completedActions.length>this.maxActionsPerNode&&(o.completedActions.shift(),o.toolCallMessages.shift()),o.updatedAt=Date.now(),m.debug("NODE_CONTEXT",`Recorded action for ${e}`,{type:c,toolName:t,target:u,success:r,totalActions:o.completedActions.length,totalToolMessages:o.toolCallMessages.length});}getToolCallMessages(e){let t=this.getSnapshot(e);return t?t.toolCallMessages:[]}hasToolCallHistory(e){let t=this.getSnapshot(e);return t!==void 0&&t.toolCallMessages.length>0}appendPartialOutput(e,t){let s=this.getOrCreateSnapshot(e);s.partialOutput+=t,s.updatedAt=Date.now(),s.partialOutput.length>5e3&&(s.partialOutput=s.partialOutput.slice(-5e3));}incrementRetryCount(e){let t=this.getOrCreateSnapshot(e);return t.retryCount++,t.updatedAt=Date.now(),t.retryCount}buildResumePrompt(e){let t=this.getSnapshot(e);if(!t||t.completedActions.length===0)return null;let s=["\u3010\u91CD\u8981\u63D0\u793A\u3011\u8FD9\u662F\u4E00\u4E2A\u91CD\u8BD5\u8BF7\u6C42\u3002\u5728\u4E4B\u524D\u7684\u5C1D\u8BD5\u4E2D\uFF0C\u4EE5\u4E0B\u64CD\u4F5C\u5DF2\u7ECF\u6210\u529F\u5B8C\u6210\uFF1A",""],n=this.groupActionsByType(t.completedActions);for(let[r,i]of Object.entries(n)){if(i.length===0)continue;let o=this.getTypeLabel(r);s.push(`## ${o} (${i.length} \u9879\u5DF2\u5B8C\u6210)`);for(let l of i){let c=l.success?"\u2713":"\u2717";s.push(`- ${c} ${l.target}: ${l.summary}`);}s.push("");}return s.push("\u8BF7\u4ECE\u4E0A\u6B21\u4E2D\u65AD\u7684\u5730\u65B9\u7EE7\u7EED\uFF0C\u4E0D\u8981\u91CD\u590D\u6267\u884C\u5DF2\u5B8C\u6210\u7684\u64CD\u4F5C\u3002"),s.push("\u5982\u679C\u67D0\u4E2A\u6587\u4EF6\u5DF2\u7ECF\u88AB\u7F16\u8F91\u8FC7\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u72B6\u6001\u800C\u4E0D\u662F\u518D\u6B21\u7F16\u8F91\u3002"),s.push(""),s.join(`
2661
2661
  `)}isActionCompleted(e,t,s){let n=this.getSnapshot(e);return n?n.completedActions.some(r=>r.toolName===t&&r.target===s&&r.success):false}getCompletedFileEdits(e){let t=this.getSnapshot(e);return t?t.completedActions.filter(s=>(s.type==="file_edit"||s.type==="file_write")&&s.success).map(s=>s.target):[]}clearSnapshot(e){this.snapshots.delete(e),m.debug("NODE_CONTEXT",`Cleared snapshot for ${e}`);}clearAll(){this.snapshots.clear(),m.debug("NODE_CONTEXT","Cleared all snapshots");}getStats(){let e=0;for(let t of this.snapshots.values())e+=t.completedActions.length;return {nodeCount:this.snapshots.size,totalActions:e}}extractTarget(e,t){if(t.file_path)return t.file_path;if(t.path)return t.path;if(t.file)return t.file;if(t.command){let s=String(t.command);return s.length>50?s.substring(0,50)+"...":s}return t.pattern?`pattern: ${t.pattern}`:t.query?`query: ${t.query}`:t.url?t.url:e}generateSummary(e,t,s,n){if(!n)return `\u5931\u8D25: ${s.substring(0,this.maxSummaryLength)}`;let r=e.toLowerCase();if(r.includes("edit")){let i=t.old_string||t.old_str||"",o=t.new_string||t.new_str||"";return i&&o?`\u66FF\u6362 "${this.truncate(i,30)}" \u2192 "${this.truncate(o,30)}"`:"\u5DF2\u7F16\u8F91"}return r.includes("write")||r.includes("create")?`\u5199\u5165 ${(t.content||"").split(`
2662
2662
  `).length} \u884C`:r.includes("read")||r.includes("view")?`\u8BFB\u53D6 ${s.split(`
2663
2663
  `).length} \u884C`:r==="bash"||r.includes("command")?`\u6267\u884C\u5B8C\u6210 (${s.split(`
2664
2664
  `).length} \u884C\u8F93\u51FA)`:r.includes("search")||r.includes("grep")||r.includes("glob")?`\u627E\u5230 ${s.split(`
2665
- `).filter(o=>o.trim()).length} \u4E2A\u7ED3\u679C`:this.truncate(s,this.maxSummaryLength)}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}groupActionsByType(e){let t={file_edit:[],file_write:[],file_read:[],command:[],search:[],web:[],other:[]};for(let s of e)t[s.type].push(s);return t}getTypeLabel(e){return {file_edit:"\u{1F4DD} \u6587\u4EF6\u7F16\u8F91",file_write:"\u{1F4C4} \u6587\u4EF6\u521B\u5EFA",file_read:"\u{1F4D6} \u6587\u4EF6\u8BFB\u53D6",command:"\u26A1 \u547D\u4EE4\u6267\u884C",search:"\u{1F50D} \u641C\u7D22\u64CD\u4F5C",web:"\u{1F310} \u7F51\u7EDC\u8BF7\u6C42",other:"\u{1F527} \u5176\u4ED6\u64CD\u4F5C"}[e]||e}};function gc(){return new Fo}W();var vC={maxConcurrency:5,nodeTimeout:3e5,allowPartialFailure:true,retryCount:2,retryDelay:1e3},jo=class{config;llmCall;onEvent;onText;onRuntimeEvent;instanceManager;promptBuilder;nodeContextManager;constructor(e){this.config={...vC,...e.config},this.llmCall=e.llmCall,this.onEvent=e.onEvent,this.onText=e.onText,this.onRuntimeEvent=e.onRuntimeEvent,this.instanceManager=dc({llmCall:this.llmCall,onEvent:this.onEvent,defaultTimeout:this.config.nodeTimeout}),this.promptBuilder=mc(),this.nodeContextManager=gc();}async execute(e,t){let s=Date.now(),n=new Map,r=[],i=pc(e.id,t);e.state.phase="executing",e.state.startedAt=s,this.emitEvent({type:"execution_start",timestamp:s,data:{dagId:e.id}});try{for(let u=0;u<e.analysis.levels.length;u++){let d=e.analysis.levels[u];e.state.currentLevel=u,this.emitEvent({type:"level_start",timestamp:Date.now(),data:{dagId:e.id,level:u}});let p=await this.executeLevel(e,d,i,n,r),h=p.filter(g=>!g.success);if(h.length>0){if(!this.config.allowPartialFailure)throw new Error(`Level ${u} failed: ${h.map(g=>g.nodeId).join(", ")}`);for(let g of h)e.state.failedNodes.push(g.nodeId);}for(let g of p)g.success&&e.state.completedNodes.push(g.nodeId);this.emitEvent({type:"level_complete",timestamp:Date.now(),data:{dagId:e.id,level:u,progress:(u+1)/e.analysis.levels.length}});}let o=Date.now();e.state.phase="completed",e.state.completedAt=o;let l=this.collectFinalOutput(e,n,i),c={dagId:e.id,success:e.state.failedNodes.length===0,completedNodes:e.state.completedNodes.length,failedNodes:e.state.failedNodes.length,totalDuration:o-s,nodeResults:n,finalOutput:l,errors:r};return this.emitEvent({type:"execution_complete",timestamp:o,data:{dagId:e.id,progress:1}}),c}catch(o){let l=Date.now();e.state.phase="failed",e.state.completedAt=l;let c=o instanceof Error?o.message:String(o);return this.emitEvent({type:"execution_failed",timestamp:l,data:{dagId:e.id,error:c}}),{dagId:e.id,success:false,completedNodes:e.state.completedNodes.length,failedNodes:e.state.failedNodes.length,totalDuration:l-s,nodeResults:n,finalOutput:`\u6267\u884C\u5931\u8D25: ${c}`,errors:[...r,{nodeId:"dag",error:c}]}}}async executeLevel(e,t,s,n,r){let i=this.chunkArray(t,this.config.maxConcurrency),o=[];for(let l of i){let c=l.map(async d=>{let p=e.nodes.get(d);return p?this.executeNodeWithRetry(p,s,n,r):(r.push({nodeId:d,error:"\u8282\u70B9\u4E0D\u5B58\u5728"}),{nodeId:d,success:false})}),u=await Promise.all(c);o.push(...u);}return o}async executeNodeWithRetry(e,t,s,n){let r=null;for(let o=0;o<=this.config.retryCount;o++){o>0&&(this.nodeContextManager.incrementRetryCount(e.id),this.emitEvent({type:"node_retry",timestamp:Date.now(),data:{nodeId:e.id,role:e.task.role,retryCount:o,maxRetries:this.config.retryCount,error:r?.message??"\u672A\u77E5\u9519\u8BEF",completedActions:this.nodeContextManager.getSnapshot(e.id)?.completedActions.length??0}}),await this.sleep(this.config.retryDelay));try{let l=o>0?this.nodeContextManager.buildResumePrompt(e.id):null,c=o>0,u=await this.executeNode(e,t,l,c);return s.set(e.id,u),t.storeNodeOutput(e.id,e.io.outputKey,u.output),e.status="completed",this.nodeContextManager.clearSnapshot(e.id),this.emitEvent({type:"node_complete",timestamp:Date.now(),data:{nodeId:e.id,result:u}}),{nodeId:e.id,success:!0}}catch(l){r=l instanceof Error?l:new Error(String(l)),m.warn("DAG_EXECUTOR",`Node ${e.id} failed (attempt ${o+1}):`,{error:r.message,completedActions:this.nodeContextManager.getSnapshot(e.id)?.completedActions.length??0});}}e.status="failed";let i=r?.message??"\u672A\u77E5\u9519\u8BEF";return n.push({nodeId:e.id,error:i}),this.nodeContextManager.clearSnapshot(e.id),this.emitEvent({type:"node_failed",timestamp:Date.now(),data:{nodeId:e.id,error:i}}),{nodeId:e.id,success:false}}async executeNode(e,t,s,n){let r=Date.now();e.status="running",this.emitEvent({type:"node_start",timestamp:r,data:{nodeId:e.id,isRetry:!!s}});let i=t.resolveInputMapping(e.io.inputMapping),o=this.promptBuilder.build({taskDescription:e.task.description,role:e.task.role,resolvedInputs:i,contextSummary:t.getSummary()}),l=s?`${s}
2665
+ `).filter(o=>o.trim()).length} \u4E2A\u7ED3\u679C`:this.truncate(s,this.maxSummaryLength)}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}groupActionsByType(e){let t={file_edit:[],file_write:[],file_read:[],command:[],search:[],web:[],other:[]};for(let s of e)t[s.type].push(s);return t}getTypeLabel(e){return {file_edit:"\u{1F4DD} \u6587\u4EF6\u7F16\u8F91",file_write:"\u{1F4C4} \u6587\u4EF6\u521B\u5EFA",file_read:"\u{1F4D6} \u6587\u4EF6\u8BFB\u53D6",command:"\u26A1 \u547D\u4EE4\u6267\u884C",search:"\u{1F50D} \u641C\u7D22\u64CD\u4F5C",web:"\u{1F310} \u7F51\u7EDC\u8BF7\u6C42",other:"\u{1F527} \u5176\u4ED6\u64CD\u4F5C"}[e]||e}};function gc(){return new Fo}W();var wC={maxConcurrency:5,nodeTimeout:3e5,allowPartialFailure:true,retryCount:2,retryDelay:1e3},jo=class{config;llmCall;onEvent;onText;onRuntimeEvent;instanceManager;promptBuilder;nodeContextManager;constructor(e){this.config={...wC,...e.config},this.llmCall=e.llmCall,this.onEvent=e.onEvent,this.onText=e.onText,this.onRuntimeEvent=e.onRuntimeEvent,this.instanceManager=dc({llmCall:this.llmCall,onEvent:this.onEvent,defaultTimeout:this.config.nodeTimeout}),this.promptBuilder=mc(),this.nodeContextManager=gc();}async execute(e,t){let s=Date.now(),n=new Map,r=[],i=pc(e.id,t);e.state.phase="executing",e.state.startedAt=s,this.emitEvent({type:"execution_start",timestamp:s,data:{dagId:e.id}});try{for(let u=0;u<e.analysis.levels.length;u++){let d=e.analysis.levels[u];e.state.currentLevel=u,this.emitEvent({type:"level_start",timestamp:Date.now(),data:{dagId:e.id,level:u}});let p=await this.executeLevel(e,d,i,n,r),h=p.filter(g=>!g.success);if(h.length>0){if(!this.config.allowPartialFailure)throw new Error(`Level ${u} failed: ${h.map(g=>g.nodeId).join(", ")}`);for(let g of h)e.state.failedNodes.push(g.nodeId);}for(let g of p)g.success&&e.state.completedNodes.push(g.nodeId);this.emitEvent({type:"level_complete",timestamp:Date.now(),data:{dagId:e.id,level:u,progress:(u+1)/e.analysis.levels.length}});}let o=Date.now();e.state.phase="completed",e.state.completedAt=o;let l=this.collectFinalOutput(e,n,i),c={dagId:e.id,success:e.state.failedNodes.length===0,completedNodes:e.state.completedNodes.length,failedNodes:e.state.failedNodes.length,totalDuration:o-s,nodeResults:n,finalOutput:l,errors:r};return this.emitEvent({type:"execution_complete",timestamp:o,data:{dagId:e.id,progress:1}}),c}catch(o){let l=Date.now();e.state.phase="failed",e.state.completedAt=l;let c=o instanceof Error?o.message:String(o);return this.emitEvent({type:"execution_failed",timestamp:l,data:{dagId:e.id,error:c}}),{dagId:e.id,success:false,completedNodes:e.state.completedNodes.length,failedNodes:e.state.failedNodes.length,totalDuration:l-s,nodeResults:n,finalOutput:`\u6267\u884C\u5931\u8D25: ${c}`,errors:[...r,{nodeId:"dag",error:c}]}}}async executeLevel(e,t,s,n,r){let i=this.chunkArray(t,this.config.maxConcurrency),o=[];for(let l of i){let c=l.map(async d=>{let p=e.nodes.get(d);return p?this.executeNodeWithRetry(p,s,n,r):(r.push({nodeId:d,error:"\u8282\u70B9\u4E0D\u5B58\u5728"}),{nodeId:d,success:false})}),u=await Promise.all(c);o.push(...u);}return o}async executeNodeWithRetry(e,t,s,n){let r=null;for(let o=0;o<=this.config.retryCount;o++){o>0&&(this.nodeContextManager.incrementRetryCount(e.id),this.emitEvent({type:"node_retry",timestamp:Date.now(),data:{nodeId:e.id,role:e.task.role,retryCount:o,maxRetries:this.config.retryCount,error:r?.message??"\u672A\u77E5\u9519\u8BEF",completedActions:this.nodeContextManager.getSnapshot(e.id)?.completedActions.length??0}}),await this.sleep(this.config.retryDelay));try{let l=o>0?this.nodeContextManager.buildResumePrompt(e.id):null,c=o>0,u=await this.executeNode(e,t,l,c);return s.set(e.id,u),t.storeNodeOutput(e.id,e.io.outputKey,u.output),e.status="completed",this.nodeContextManager.clearSnapshot(e.id),this.emitEvent({type:"node_complete",timestamp:Date.now(),data:{nodeId:e.id,result:u}}),{nodeId:e.id,success:!0}}catch(l){r=l instanceof Error?l:new Error(String(l)),m.warn("DAG_EXECUTOR",`Node ${e.id} failed (attempt ${o+1}):`,{error:r.message,completedActions:this.nodeContextManager.getSnapshot(e.id)?.completedActions.length??0});}}e.status="failed";let i=r?.message??"\u672A\u77E5\u9519\u8BEF";return n.push({nodeId:e.id,error:i}),this.nodeContextManager.clearSnapshot(e.id),this.emitEvent({type:"node_failed",timestamp:Date.now(),data:{nodeId:e.id,error:i}}),{nodeId:e.id,success:false}}async executeNode(e,t,s,n){let r=Date.now();e.status="running",this.emitEvent({type:"node_start",timestamp:r,data:{nodeId:e.id,isRetry:!!s}});let i=t.resolveInputMapping(e.io.inputMapping),o=this.promptBuilder.build({taskDescription:e.task.description,role:e.task.role,resolvedInputs:i,contextSummary:t.getSummary()}),l=s?`${s}
2666
2666
 
2667
2667
  ---
2668
2668
 
@@ -3099,7 +3099,7 @@ ${e.result.output}
3099
3099
  - \u4EFB\u52A1\u5206\u89E3\u65B9\u6848
3100
3100
  - \u6267\u884C\u8BA1\u5212
3101
3101
  - \u8FDB\u5EA6\u62A5\u544A
3102
- - \u98CE\u9669\u8BC4\u4F30`,priority:0},defaultCapabilities:["*"],defaultSpecializations:["task-decomposition","coordination","planning"]}},yc=class{llmCall;executionCapability;defaultHeartbeatInterval;defaultMaxConcurrentTasks;constructor(e){this.llmCall=e.llmCall,this.executionCapability=e.executionCapability,this.defaultHeartbeatInterval=e.defaultHeartbeatInterval??3e4,this.defaultMaxConcurrentTasks=e.defaultMaxConcurrentTasks??3;}createFromRole(e,t){let s=fc[e];if(!s)throw new Error(`Unknown role: ${e}`);let n={...s.role,systemPrompt:t?.systemPromptOverride??s.role.systemPrompt},r=[...s.defaultCapabilities,...t?.additionalCapabilities??[]],i=[...s.defaultSpecializations,...t?.additionalSpecializations??[]],o={role:n,capabilities:r,specializations:i,llmCall:this.llmCall,executionCapability:this.executionCapability,heartbeatInterval:t?.heartbeatInterval??this.defaultHeartbeatInterval,maxConcurrentTasks:t?.maxConcurrentTasks??this.defaultMaxConcurrentTasks,metadata:t?.metadata};return new Ir(o)}createCustom(e){let s={role:{name:e.name,description:e.description,systemPrompt:e.systemPrompt,priority:e.priority??1},capabilities:e.capabilities,specializations:e.specializations,llmCall:this.llmCall,executionCapability:this.executionCapability,heartbeatInterval:e.options?.heartbeatInterval??this.defaultHeartbeatInterval,maxConcurrentTasks:e.options?.maxConcurrentTasks??this.defaultMaxConcurrentTasks,metadata:e.options?.metadata};return new Ir(s)}createDefaultTeam(){let e=new Map,t=["coordinator","programmer","reviewer","tester"];for(let s of t)e.set(s,this.createFromRole(s));return e}createTeamForTask(e){let t=[],s=e.toLowerCase();return t.push(this.createFromRole("coordinator")),(s.includes("\u524D\u7AEF")||s.includes("ui")||s.includes("react"))&&t.push(this.createFromRole("frontend")),(s.includes("\u540E\u7AEF")||s.includes("api")||s.includes("backend"))&&t.push(this.createFromRole("backend")),(s.includes("\u5168\u6808")||s.includes("fullstack"))&&t.push(this.createFromRole("fullstack")),(s.includes("\u5B89\u5168")||s.includes("security")||s.includes("\u6F0F\u6D1E"))&&t.push(this.createFromRole("security")),(s.includes("\u6D4B\u8BD5")||s.includes("test"))&&t.push(this.createFromRole("tester")),(s.includes("\u90E8\u7F72")||s.includes("docker")||s.includes("ci"))&&t.push(this.createFromRole("devops")),(s.includes("\u67B6\u6784")||s.includes("\u8BBE\u8BA1")||s.includes("architecture"))&&t.push(this.createFromRole("architect")),(s.includes("\u6587\u6863")||s.includes("document"))&&t.push(this.createFromRole("documenter")),(s.includes("\u8C03\u8BD5")||s.includes("debug")||s.includes("bug"))&&t.push(this.createFromRole("debugger")),(s.includes("\u6570\u636E")||s.includes("data")||s.includes("\u5206\u6790"))&&t.push(this.createFromRole("data")),t.length===1&&t.push(this.createFromRole("programmer")),t.some(n=>n.role.name==="\u4EE3\u7801\u5BA1\u67E5\u5458")||t.push(this.createFromRole("reviewer")),t}static getPredefinedRoles(){return Object.values(fc)}static getRoleTemplate(e){return fc[e]}};function Am(a){return new yc(a)}var CC=[{id:"typescript",name:"TypeScript",description:"TypeScript \u7F16\u7A0B",level:5,tags:["languages","javascript"]},{id:"javascript",name:"JavaScript",description:"JavaScript \u7F16\u7A0B",level:5,tags:["languages"]},{id:"python",name:"Python",description:"Python \u7F16\u7A0B",level:5,tags:["languages"]},{id:"go",name:"Go",description:"Go \u7F16\u7A0B",level:4,tags:["languages"]},{id:"rust",name:"Rust",description:"Rust \u7F16\u7A0B",level:4,tags:["languages"]},{id:"java",name:"Java",description:"Java \u7F16\u7A0B",level:4,tags:["languages"]},{id:"react",name:"React",description:"React \u524D\u7AEF\u5F00\u53D1",level:5,tags:["frameworks","frontend"]},{id:"vue",name:"Vue",description:"Vue \u524D\u7AEF\u5F00\u53D1",level:4,tags:["frameworks","frontend"]},{id:"nodejs",name:"Node.js",description:"Node.js \u540E\u7AEF\u5F00\u53D1",level:5,tags:["frameworks","backend"]},{id:"express",name:"Express",description:"Express Web \u6846\u67B6",level:4,tags:["frameworks","backend"]},{id:"nextjs",name:"Next.js",description:"Next.js \u5168\u6808\u6846\u67B6",level:4,tags:["frameworks","fullstack"]},{id:"coding",name:"\u7F16\u7A0B\u5B9E\u73B0",description:"\u4EE3\u7801\u7F16\u5199\u548C\u5B9E\u73B0",level:5,tags:["skills","core"]},{id:"debugging",name:"\u8C03\u8BD5",description:"\u95EE\u9898\u8C03\u8BD5\u548C\u4FEE\u590D",level:4,tags:["skills","core"]},{id:"refactoring",name:"\u91CD\u6784",description:"\u4EE3\u7801\u91CD\u6784\u548C\u4F18\u5316",level:4,tags:["skills","core"]},{id:"testing",name:"\u6D4B\u8BD5",description:"\u7F16\u5199\u548C\u6267\u884C\u6D4B\u8BD5",level:4,tags:["skills","quality"]},{id:"review",name:"\u4EE3\u7801\u8BC4\u5BA1",description:"\u4EE3\u7801\u5BA1\u67E5\u548C\u53CD\u9988",level:4,tags:["skills","quality"]},{id:"documentation",name:"\u6587\u6863",description:"\u7F16\u5199\u6280\u672F\u6587\u6863",level:3,tags:["skills","communication"]},{id:"architecture",name:"\u67B6\u6784\u8BBE\u8BA1",description:"\u7CFB\u7EDF\u67B6\u6784\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"design",name:"\u8BBE\u8BA1",description:"\u8F6F\u4EF6\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"api-design",name:"API \u8BBE\u8BA1",description:"API \u63A5\u53E3\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"database-design",name:"\u6570\u636E\u5E93\u8BBE\u8BA1",description:"\u6570\u636E\u5E93\u67B6\u6784\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"git",name:"Git",description:"Git \u7248\u672C\u63A7\u5236",level:5,tags:["tools","vcs"]},{id:"docker",name:"Docker",description:"Docker \u5BB9\u5668\u5316",level:4,tags:["tools","devops"]},{id:"ci-cd",name:"CI/CD",description:"\u6301\u7EED\u96C6\u6210\u548C\u90E8\u7F72",level:4,tags:["tools","devops"]},{id:"shell",name:"Shell",description:"Shell \u811A\u672C\u7F16\u5199",level:4,tags:["tools","scripting"]},{id:"security",name:"\u5B89\u5168",description:"\u5B89\u5168\u5F00\u53D1\u5B9E\u8DF5",level:4,tags:["domains","security"]},{id:"performance",name:"\u6027\u80FD\u4F18\u5316",description:"\u6027\u80FD\u5206\u6790\u548C\u4F18\u5316",level:4,tags:["domains","optimization"]},{id:"frontend",name:"\u524D\u7AEF\u5F00\u53D1",description:"\u524D\u7AEF\u5F00\u53D1\u7EFC\u5408",level:5,tags:["domains","web"]},{id:"backend",name:"\u540E\u7AEF\u5F00\u53D1",description:"\u540E\u7AEF\u5F00\u53D1\u7EFC\u5408",level:5,tags:["domains","web"]},{id:"fullstack",name:"\u5168\u6808\u5F00\u53D1",description:"\u5168\u6808\u5F00\u53D1\u7EFC\u5408",level:4,tags:["domains","web"]},{id:"devops",name:"DevOps",description:"DevOps \u5B9E\u8DF5",level:4,tags:["domains","operations"]},{id:"ai-ml",name:"AI/ML",description:"\u4EBA\u5DE5\u667A\u80FD\u548C\u673A\u5668\u5B66\u4E60",level:3,tags:["domains","ai"]}],bc=class{capabilities=new Map;constructor(){for(let e of CC)this.capabilities.set(e.id,e);}getCapability(e){return this.capabilities.get(e)}registerCapability(e){this.capabilities.set(e.id,e);}listCapabilities(){return Array.from(this.capabilities.values())}listByCategory(e){return Array.from(this.capabilities.values()).filter(t=>t.tags.includes(e))}calculateMatch(e,t){if(e.length===0||t.includes("*"))return 1;let s=0,n=0;for(let o of e)if(t.includes(o)){s++;let l=this.capabilities.get(o);n+=l?l.level/5:.8;}else {let l=this.capabilities.get(o);if(l)for(let c of t){let u=this.capabilities.get(c);if(u&&this.hasCommonTag(l,u)){s+=.5,n+=.5*(u.level/5);break}}}let r=s/e.length,i=s>0?n/s:0;return r*.7+i*.3}hasCommonTag(e,t){return e.tags.some(s=>t.tags.includes(s))}inferCapabilities(e){let t=[],s=e.toLowerCase(),n={typescript:["typescript","ts",".ts"],javascript:["javascript","js",".js"],python:["python","py",".py"],react:["react","jsx","tsx","component"],nodejs:["node","express","backend"],testing:["test","jest","mocha","spec"],debugging:["debug","fix","bug","error"],refactoring:["refactor","optimize","improve"],documentation:["document","readme","docs"],security:["security","auth","encrypt","password"],database:["database","sql","mongodb","redis"],api:["api","rest","graphql","endpoint"]};for(let[r,i]of Object.entries(n))i.some(o=>s.includes(o))&&t.push(r);return t.length===0&&t.push("coding"),t}},Em=new bc;var Bo=class extends EventEmitter{agents=new Map;agentInstances=new Map;config;healthCheckTimer;started=false;constructor(e){super(),this.config={heartbeatTimeout:e?.heartbeatTimeout??9e4,healthCheckInterval:e?.healthCheckInterval??3e4,maxAgents:e?.maxAgents??100,autoCleanup:e?.autoCleanup??true};}start(){this.started||(this.started=true,this.config.autoCleanup&&this.startHealthCheck(),this.emit("started"));}stop(){this.started&&(this.started=false,this.stopHealthCheck(),this.emit("stopped"));}register(e){if(this.agents.size>=this.config.maxAgents)throw new Error(`Registry full: max ${this.config.maxAgents} agents`);let t=e.getRegistration();if(this.agents.has(t.id))throw new Error(`Agent already registered: ${t.id}`);return this.agents.set(t.id,t),this.agentInstances.set(t.id,e),this.setupAgentListeners(e),this.emit("agent_registered",{agentId:t.id,registration:t,timestamp:Date.now()}),t}registerMany(e){return e.map(t=>this.register(t))}unregister(e,t){if(!this.agents.get(e))return false;let n=this.agentInstances.get(e);return n&&(n.removeAllListeners(),n.stop()),this.agents.delete(e),this.agentInstances.delete(e),this.emit("agent_unregistered",{agentId:e,reason:t??"manual",timestamp:Date.now()}),true}updateStatus(e,t,s){let n=this.agents.get(e);if(!n)return;let r=n.status;n.status=t,this.emit("agent_status_changed",{agentId:e,previousStatus:r,newStatus:t,reason:s,timestamp:Date.now()});}handleHeartbeat(e){let t=this.agents.get(e.agentId);t&&(t.lastHeartbeat=e.timestamp,t.status=e.status,t.availability=e.availability,this.emit("agent_heartbeat",{...e,timestamp:Date.now()}));}get(e){return this.agents.get(e)}getInstance(e){return this.agentInstances.get(e)}getAll(){return Array.from(this.agents.values())}listAll(){return this.getAll()}getActive(){return this.getAll().filter(e=>e.status==="active"||e.status==="busy")}query(e){let t=this.getAll();if(e.status){let i=Array.isArray(e.status)?e.status:[e.status];t=t.filter(o=>i.includes(o.status));}e.minAvailability!==void 0&&(t=t.filter(i=>i.availability>=e.minAvailability)),e.minReputation!==void 0&&(t=t.filter(i=>i.reputation>=e.minReputation));let s=t.map(i=>{let o=this.calculateMatchDetails(i,e);return {agent:i,score:this.calculateOverallScore(o),details:o}}),n=e.requiredCapabilities?.length?s.filter(i=>i.details.capabilityMatch>=.5):s,r=e.sortBy??"match";return n.sort((i,o)=>{switch(r){case "availability":return o.agent.availability-i.agent.availability;case "reputation":return o.agent.reputation-i.agent.reputation;case "priority":return (i.agent.role.priority??1)-(o.agent.role.priority??1);default:return o.score-i.score}}),e.limit?n.slice(0,e.limit):n}findBestMatch(e){let t=this.query({status:["active","busy"],requiredCapabilities:e,minAvailability:.1,sortBy:"match",limit:1});if(t[0])return t[0];let s=this.getActive();if(s.length>0){s.sort((r,i)=>{let o=r.reputation*.6+r.availability*.4;return i.reputation*.6+i.availability*.4-o});let n=s[0];return {agent:n,score:.5,details:{capabilityMatch:.5,availabilityScore:n.availability,reputationScore:n.reputation/5,specializationBonus:0}}}}findMatches(e,t){let s=this.query({status:["active","busy"],requiredCapabilities:e,minAvailability:.1,sortBy:"match",limit:t});if(s.length>=t)return s;let n=t-s.length,r=new Set(s.map(o=>o.agent.id)),i=this.getActive().filter(o=>!r.has(o.id)).slice(0,n);for(let o of i)s.push({agent:o,score:.5,details:{capabilityMatch:.5,availabilityScore:o.availability,reputationScore:o.reputation/5,specializationBonus:0}});return s}groupByCapability(){let e=new Map;for(let t of this.agents.values())for(let s of t.capabilities)e.has(s)||e.set(s,[]),e.get(s).push(t);return e}getStats(){let e=this.getAll(),t={total:e.length,active:0,busy:0,paused:0,offline:0,avgAvailability:0,avgReputation:0},s=0,n=0;for(let r of e){switch(r.status){case "active":t.active++;break;case "busy":t.busy++;break;case "paused":t.paused++;break;case "offline":t.offline++;break}s+=r.availability,n+=r.reputation;}return e.length>0&&(t.avgAvailability=s/e.length,t.avgReputation=n/e.length),t}calculateMatchDetails(e,t){let s=t.requiredCapabilities?.length?Em.calculateMatch(t.requiredCapabilities,e.capabilities):1,n=e.availability,r=e.reputation/5,i=0;return t.specializations?.length&&e.specializations.length&&(i=t.specializations.filter(l=>e.specializations.includes(l)).length/t.specializations.length*.2),{capabilityMatch:s,availabilityScore:n,reputationScore:r,specializationBonus:i}}calculateOverallScore(e){return e.capabilityMatch*.4+e.availabilityScore*.25+e.reputationScore*.25+e.specializationBonus}setupAgentListeners(e){e.on("heartbeat",t=>{this.handleHeartbeat(t);}),e.on("status_changed",t=>{this.updateStatus(t.agentId,t.newStatus);});}startHealthCheck(){this.healthCheckTimer=setInterval(()=>{this.performHealthCheck();},this.config.healthCheckInterval);}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=void 0);}performHealthCheck(){let e=Date.now(),t=[];for(let[s,n]of this.agents)e-n.lastHeartbeat>this.config.heartbeatTimeout&&(t.push(s),this.emit("agent_timeout",{agentId:s,lastHeartbeat:n.lastHeartbeat,timeout:this.config.heartbeatTimeout,timestamp:e}));if(this.config.autoCleanup&&t.length>0){for(let s of t)this.unregister(s,"heartbeat_timeout");this.emit("cleanup_performed",{removedAgents:t,timestamp:e});}}clear(){let e=Array.from(this.agents.keys());for(let t of e)this.unregister(t,"registry_cleared");}get size(){return this.agents.size}};function Im(a){return new Bo(a)}new Bo;var Go=class extends EventEmitter{subscribers=new Map;messageHistory=[];messageQueue=[];config;stats={sent:0,received:0,processed:0,failed:0,byType:new Map,avgProcessingTime:0};processing=false;messageCounter=0;constructor(e){super(),this.config={maxQueueSize:e?.maxQueueSize??1e3,defaultTTL:e?.defaultTTL??6e4,enablePersistence:e?.enablePersistence??false,enableReplay:e?.enableReplay??true,maxRetries:e?.maxRetries??3,retryDelay:e?.retryDelay??1e3};}async publish(e,t,s){let n={id:this.generateMessageId(),type:e,from:s?.from??"system",to:s?.to??"broadcast",payload:t,priority:s?.priority??"normal",createdAt:Date.now(),expiresAt:Date.now()+(s?.ttl??this.config.defaultTTL),correlationId:s?.correlationId,replyTo:s?.replyTo,metadata:s?.metadata};return this.enqueue(n),this.stats.sent++,this.incrementTypeStats(e),this.emit("message_published",n),await this.processQueue(),n}async publishTaskBroadcast(e){return this.publish("task_broadcast",e,{from:"coordinator",to:"broadcast",priority:e.priority,ttl:e.bidDeadline-Date.now(),correlationId:e.id})}async publishBid(e){return this.publish("bid",e,{from:e.agentId,to:"coordinator",priority:"high",correlationId:e.taskId})}async publishNegotiationMessage(e){return this.publish("negotiation",e,{from:e.from,to:e.to,priority:"high",correlationId:e.sessionId})}subscribe(e){return this.subscribers.set(e.id,e),this.emit("subscriber_added",{subscriberId:e.id,types:e.types}),()=>this.unsubscribe(e.id)}subscribeToType(e,t,s){return this.subscribe({id:e,types:[t],callback:s})}subscribeForAgent(e,t){return this.subscribe({id:`agent-${e}`,types:["task_broadcast","bid_evaluation","negotiation","execution_command","system"],callback:t,filter:s=>s.to===e||s.to==="broadcast"})}unsubscribe(e){let t=this.subscribers.delete(e);return t&&this.emit("subscriber_removed",{subscriberId:e}),t}async request(e,t,s){let n=s?.timeout??3e4,r=await this.publish(e,t,{from:s?.from,to:s?.to,priority:"high"});return new Promise((i,o)=>{let l=setTimeout(()=>{this.unsubscribe(`response-${r.id}`),o(new Error(`Request timeout: ${r.id}`));},n);this.subscribe({id:`response-${r.id}`,types:[e],callback:c=>{c.replyTo===r.id&&(clearTimeout(l),this.unsubscribe(`response-${r.id}`),i(c));}});})}async reply(e,t,s){return this.publish(e.type,t,{from:e.to==="broadcast"?"system":e.to,to:e.from,priority:s?.priority??e.priority,correlationId:e.correlationId,replyTo:e.id})}getHistory(e){let t=[...this.messageHistory];return e?.type&&(t=t.filter(s=>s.type===e.type)),e?.from&&(t=t.filter(s=>s.from===e.from)),e?.to&&(t=t.filter(s=>s.to===e.to||s.to==="broadcast")),e?.correlationId&&(t=t.filter(s=>s.correlationId===e.correlationId)),e?.since&&(t=t.filter(s=>s.createdAt>=e.since)),e?.limit&&(t=t.slice(-e.limit)),t}async replay(e,t){if(!this.config.enableReplay)throw new Error("Replay is not enabled");let s=t?.filter?e.filter(t.filter):e;for(let n of s)await this.deliverMessage(n),t?.delay&&await new Promise(r=>setTimeout(r,t.delay));}getStats(){return {...this.stats,byType:new Map(this.stats.byType)}}clearQueue(){this.messageQueue=[],this.emit("queue_cleared");}clearHistory(){this.messageHistory=[],this.emit("history_cleared");}resetStats(){this.stats={sent:0,received:0,processed:0,failed:0,byType:new Map,avgProcessingTime:0};}enqueue(e){if(this.messageQueue.length>=this.config.maxQueueSize){let r=this.messageQueue.findIndex(i=>i.priority==="low");r>=0?this.messageQueue.splice(r,1):this.messageQueue.shift();}let t={critical:0,high:1,medium:2,normal:3,low:4},s=t[e.priority]??3,n=this.messageQueue.length;for(let r=0;r<this.messageQueue.length;r++)if((t[this.messageQueue[r].priority]??3)>s){n=r;break}this.messageQueue.splice(n,0,e);}async processQueue(){if(!this.processing){this.processing=true;try{for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(e.expiresAt&&Date.now()>e.expiresAt){this.emit("message_expired",e);continue}await this.deliverMessage(e);}}finally{this.processing=false;}}}async deliverMessage(e){let t=Date.now();this.stats.received++,this.config.enableReplay&&(this.messageHistory.push(e),this.messageHistory.length>this.config.maxQueueSize*10&&(this.messageHistory=this.messageHistory.slice(-this.config.maxQueueSize*5)));let s=this.getMatchingSubscribers(e);s.sort((r,i)=>(r.priority??10)-(i.priority??10));for(let r of s)try{await r.callback(e),this.stats.processed++;}catch(i){this.stats.failed++,this.emit("delivery_error",{message:e,subscriberId:r.id,error:i});}let n=Date.now()-t;this.stats.avgProcessingTime=(this.stats.avgProcessingTime*(this.stats.received-1)+n)/this.stats.received,this.emit("message_delivered",{message:e,subscriberCount:s.length,processingTime:n});}getMatchingSubscribers(e){let t=[];for(let s of this.subscribers.values())s.types.includes(e.type)&&(s.filter&&!s.filter(e)||t.push(s));return t}generateMessageId(){return `msg-${Date.now()}-${++this.messageCounter}`}incrementTypeStats(e){let t=this.stats.byType.get(e)??0;this.stats.byType.set(e,t+1);}get subscriberCount(){return this.subscribers.size}get queueLength(){return this.messageQueue.length}};function Mm(a){return new Go(a)}new Go;W();var TC={capabilityMatch:.3,availability:.15,reputation:.2,confidence:.25,efficiency:.1},vc=class extends EventEmitter{registry;messageBus;config;weights;sessions=new Map;sessionCounter=0;constructor(e,t,s){super(),this.registry=e,this.messageBus=t,this.config={defaultTimeout:s?.defaultTimeout??3e4,minBids:s?.minBids??1,maxBids:s?.maxBids??10,selectCount:s?.selectCount??10,minAcceptScore:s?.minAcceptScore??25,parallelBidding:s?.parallelBidding??true,weights:s?.weights??TC},this.weights=this.config.weights,this.setupMessageSubscriptions();}async startBidding(e,t){let s=this.generateSessionId(),n=t?.timeout??this.config.defaultTimeout,r={id:s,task:e,bids:new Map,evaluations:new Map,status:"collecting",selectedAgents:[],createdAt:Date.now(),deadline:Date.now()+n};return this.sessions.set(s,r),this.emit("session_created",{sessionId:s,taskId:e.id,deadline:r.deadline}),t?.broadcast!==false&&await this.broadcastTask(e),this.waitForBids(r,{timeout:n,minBids:t?.minBids??this.config.minBids,selectCount:t?.selectCount??this.config.selectCount})}async requestBidsFromAgents(e,t,s){let n=this.generateSessionId(),r=s?.timeout??this.config.defaultTimeout,i={id:n,task:e,bids:new Map,evaluations:new Map,status:"collecting",selectedAgents:[],createdAt:Date.now(),deadline:Date.now()+r};this.sessions.set(n,i);let o=t.map(async l=>{let c=this.registry.getInstance(l);if(c)try{let u=await c.evaluateTask(e);s?.onAgentDecision?.({agentId:l,agentName:c.role.name,participate:u.participate,reason:u.reason,capabilityScore:u.capabilityScore,confidence:u.bid?.confidence}),this.emit("agent_bid_decision",{agentId:l,agentName:c.role.name,participate:u.participate,reason:u.reason,capabilityScore:u.capabilityScore,confidence:u.bid?.confidence}),u.participate&&u.bid&&await this.submitBid(n,u.bid);}catch(u){let d=u instanceof Error?u.message:String(u);s?.onAgentDecision?.({agentId:l,agentName:c.role.name,participate:false,reason:`\u8BC4\u4F30\u5931\u8D25: ${d}`}),this.emit("bid_request_failed",{agentId:l,error:u});}});if(this.config.parallelBidding)await Promise.all(o);else for(let l of o)await l;return this.finalizeBidding(i)}async submitBid(e,t){let s=this.sessions.get(e);return s?s.status!=="collecting"?(this.emit("bid_rejected",{bid:t,reason:"Session not collecting"}),false):Date.now()>s.deadline?(this.emit("bid_rejected",{bid:t,reason:"Deadline passed"}),false):s.bids.has(t.agentId)?(this.emit("bid_rejected",{bid:t,reason:"Already submitted"}),false):s.bids.size>=this.config.maxBids?(this.emit("bid_rejected",{bid:t,reason:"Max bids reached"}),false):(s.bids.set(t.agentId,t),this.emit("bid_received",{sessionId:e,bid:t,totalBids:s.bids.size}),true):(this.emit("bid_rejected",{bid:t,reason:"Session not found"}),false)}evaluateBid(e,t){let s=this.registry.get(e.agentId),n=this.calculateCapabilityMatch(t.requiredCapabilities,s?.capabilities??[]),r=s?.availability??0,i=(s?.reputation??3)/5,o=e.confidence,c=Math.min(1,3e5/Math.max(e.estimatedTime,1e3)),u=(n*this.weights.capabilityMatch+r*this.weights.availability+i*this.weights.reputation+o*this.weights.confidence+c*this.weights.efficiency)*100;return {bid:e,score:u,breakdown:{capabilityMatch:n*25,availabilityScore:r*25,reputationScore:i*25,confidenceScore:o*25,efficiencyScore:c*10},selected:false,rank:0}}evaluateAllBids(e){e.status="evaluating";let t=[];for(let s of e.bids.values()){let n=this.evaluateBid(s,e.task);t.push(n),e.evaluations.set(s.agentId,n);}return t.sort((s,n)=>n.score-s.score),t.forEach((s,n)=>{s.rank=n+1;}),this.emit("bids_evaluated",{sessionId:e.id,evaluations:t}),t}selectAgents(e,t,s){e.status="selecting";let n=t.filter(o=>o.score>=this.config.minAcceptScore);m.debug("BIDDING",`selectAgents: ${n.length}/${t.length} qualified (minScore=${this.config.minAcceptScore}, selectCount=${s})`);let r=n.slice(0,s);for(let o of r)o.selected=true;let i=r.map(o=>o.bid.agentId);return e.selectedAgents=i,this.emit("agents_selected",{sessionId:e.id,selectedAgents:i,evaluations:r}),i}cancelSession(e,t){let s=this.sessions.get(e);return s?(s.timer&&clearTimeout(s.timer),s.status="cancelled",s.completedAt=Date.now(),this.emit("session_cancelled",{sessionId:e,reason:t,bidsReceived:s.bids.size}),this.sessions.delete(e),true):false}getSession(e){return this.sessions.get(e)}get activeSessionCount(){return this.sessions.size}async broadcastTask(e){await this.messageBus.publishTaskBroadcast(e),this.emit("task_broadcasted",{taskId:e.id,requiredCapabilities:e.requiredCapabilities});}waitForBids(e,t){return new Promise(s=>{let n=()=>{e.bids.size>=this.config.maxBids&&(e.timer&&clearTimeout(e.timer),s(this.finalizeBidding(e,t.selectCount)));},r=i=>{i.sessionId===e.id&&n();};this.on("bid_received",r),e.timer=setTimeout(()=>{this.off("bid_received",r),e.bids.size<t.minBids?(e.status="timeout",e.completedAt=Date.now(),s({sessionId:e.id,taskId:e.task.id,success:false,selectedAgents:[],bids:Array.from(e.bids.values()),evaluations:[],failureReason:`Insufficient bids: ${e.bids.size}/${t.minBids}`,duration:Date.now()-e.createdAt}),this.sessions.delete(e.id)):s(this.finalizeBidding(e,t.selectCount));},t.timeout);})}finalizeBidding(e,t){let s=this.evaluateAllBids(e),n=t??this.config.selectCount,r=this.selectAgents(e,s,n);e.status="completed",e.completedAt=Date.now();let i={sessionId:e.id,taskId:e.task.id,success:r.length>0,selectedAgents:r,bids:Array.from(e.bids.values()),evaluations:s,duration:e.completedAt-e.createdAt};return r.length===0&&(i.failureReason="No qualified agents"),this.emit("bidding_completed",i),this.sessions.delete(e.id),i}calculateCapabilityMatch(e,t){if(e.length===0||t.includes("*"))return 1;let s=0;for(let n of e)t.includes(n)&&s++;return s/e.length}setupMessageSubscriptions(){this.messageBus.subscribeToType("bidding_engine","bid",async e=>{let t=e.payload;for(let s of this.sessions.values())if(s.task.id===t.taskId){await this.submitBid(s.id,t);break}});}generateSessionId(){return `bidding-${Date.now()}-${++this.sessionCounter}`}setWeights(e){this.weights={...this.weights,...e};}};function Pm(a,e,t){return new vc(a,e,t)}var RC={maxRounds:5,roundTimeout:6e4,consensusThreshold:.7,minParticipants:2,allowLateJoin:false,autoGenerateProposal:true},wc=class extends EventEmitter{registry;messageBus;config;sessions=new Map;sessionCounter=0;constructor(e,t,s){super(),this.registry=e,this.messageBus=t,this.config={...RC,...s},this.setupMessageSubscriptions();}setLlmCall(e){this.config.llmCall=e;}async startNegotiation(e,t,s,n){if(t.length<this.config.minParticipants)throw new Error(`Insufficient participants: ${t.length}/${this.config.minParticipants}`);let r=this.generateSessionId(),i=Date.now(),o={id:r,taskId:e.id,taskDescription:e.description??e.userRequest,participants:t,status:"active",currentRound:0,maxRounds:this.config.maxRounds,proposals:[],messages:[],votes:new Map,consensusThreshold:this.config.consensusThreshold,createdAt:i,config:{maxRounds:this.config.maxRounds,roundTimeout:this.config.roundTimeout,consensusThreshold:this.config.consensusThreshold,minParticipants:this.config.minParticipants,allowLateJoin:this.config.allowLateJoin}};this.sessions.set(r,o),this.emit("negotiation_started",{sessionId:r,taskId:e.id,participants:t});let l=n?.initialProposal;return !l&&this.config.autoGenerateProposal&&(l=await this.generateProposal(o,e,s)),l&&(o.proposals.push(l),o.currentProposal=l,this.emit("proposal_submitted",{sessionId:r,proposal:l})),o}async conductRound(e){let t=this.sessions.get(e);if(!t)throw new Error(`Session not found: ${e}`);t.currentRound++,this.emit("round_started",{sessionId:e,round:t.currentRound});let s=[];for(let i of t.participants){let o=this.registry.getInstance(i);if(!(!o||!t.currentProposal))try{let l=await o.participateInNegotiation(e,t.currentProposal,{taskDescription:t.taskDescription??t.taskId,otherParticipants:t.participants});l.round=t.currentRound,s.push(l),t.messages.push(l),this.emit("message_received",{sessionId:e,message:l});}catch(l){this.emit("participant_error",{sessionId:e,participantId:i,error:l});}}let n=this.analyzeRoundMessages(s);if(n.hasConcerns&&t.currentProposal&&this.config.llmCall){let i=await this.refineProposal(t,t.currentProposal,n.concerns,n.suggestions);i&&(t.currentProposal=i,t.proposals.push(i),this.emit("proposal_updated",{sessionId:e,proposal:i}));}let r=this.checkConsensus(s);return this.emit("round_completed",{sessionId:e,round:t.currentRound,messageCount:s.length,consensusReached:r}),{round:t.currentRound,messages:s,consensusReached:r}}async startVoting(e){let t=this.sessions.get(e);if(!t||!t.currentProposal)throw new Error(`Session or proposal not found: ${e}`);this.emit("voting_started",{sessionId:e,proposalId:t.currentProposal.id});let s=new Map;for(let r of t.participants){let i=t.messages.filter(o=>o.from===r).pop();i?.data?.vote?s.set(r,i.data.vote):s.set(r,"abstain"),this.emit("vote_cast",{sessionId:e,agentId:r,vote:s.get(r)});}t.votes=s;let n=this.calculateVotingResult(t,s);return this.emit("voting_completed",{sessionId:e,result:n}),n}async runFullNegotiation(e,t,s){let n=Date.now(),r=await this.startNegotiation(e,t,s),i=false;for(;r.currentRound<r.maxRounds&&!i&&(i=(await this.conductRound(r.id)).consensusReached,!i);)await new Promise(d=>setTimeout(d,1e3));let o=await this.startVoting(r.id);o.approved?(r.status="completed",r.consensusProposal=r.currentProposal,this.emit("consensus_reached",{sessionId:r.id,proposal:r.currentProposal})):(r.status="failed",this.emit("negotiation_failed",{sessionId:r.id,reason:"Voting rejected",rounds:r.currentRound})),r.completedAt=Date.now();let l=r,c=r.messages.length;return this.sessions.delete(r.id),{success:o.approved,proposal:o.approved?r.currentProposal:void 0,result:o,rounds:r.currentRound,duration:Date.now()-n,session:l,messageCount:c}}async generateProposal(e,t,s){let n=`proposal-${e.id}-${e.proposals.length+1}`,r=[],i=[[]];for(let l=0;l<s.length;l++){let c=s[l],u=`subtask-${l+1}`;r.push({id:u,description:`\u5B50\u4EFB\u52A1 ${l+1}: ${c.proposedApproach}`,assignedAgent:c.agentId,estimatedTime:c.estimatedTime,estimatedTokens:c.resourceRequirements.estimatedTokens,dependencies:l>0?[`subtask-${l}`]:[],priority:1}),r[l].dependencies.length===0?i[0].push(u):(i[1]||(i[1]=[]),i[1].push(u));}return {id:n,sessionId:e.id,proposer:"system",version:1,subtasks:r,executionLevels:i,estimatedTotalTime:r.reduce((l,c)=>l+c.estimatedTime,0),estimatedTotalTokens:r.reduce((l,c)=>l+c.estimatedTokens,0),risks:[],createdAt:Date.now()}}async refineProposal(e,t,s,n){if(!this.config.llmCall)return null;let r=`
3102
+ - \u98CE\u9669\u8BC4\u4F30`,priority:0},defaultCapabilities:["*"],defaultSpecializations:["task-decomposition","coordination","planning"]}},yc=class{llmCall;executionCapability;defaultHeartbeatInterval;defaultMaxConcurrentTasks;constructor(e){this.llmCall=e.llmCall,this.executionCapability=e.executionCapability,this.defaultHeartbeatInterval=e.defaultHeartbeatInterval??3e4,this.defaultMaxConcurrentTasks=e.defaultMaxConcurrentTasks??3;}createFromRole(e,t){let s=fc[e];if(!s)throw new Error(`Unknown role: ${e}`);let n={...s.role,systemPrompt:t?.systemPromptOverride??s.role.systemPrompt},r=[...s.defaultCapabilities,...t?.additionalCapabilities??[]],i=[...s.defaultSpecializations,...t?.additionalSpecializations??[]],o={role:n,capabilities:r,specializations:i,llmCall:this.llmCall,executionCapability:this.executionCapability,heartbeatInterval:t?.heartbeatInterval??this.defaultHeartbeatInterval,maxConcurrentTasks:t?.maxConcurrentTasks??this.defaultMaxConcurrentTasks,metadata:t?.metadata};return new Ir(o)}createCustom(e){let s={role:{name:e.name,description:e.description,systemPrompt:e.systemPrompt,priority:e.priority??1},capabilities:e.capabilities,specializations:e.specializations,llmCall:this.llmCall,executionCapability:this.executionCapability,heartbeatInterval:e.options?.heartbeatInterval??this.defaultHeartbeatInterval,maxConcurrentTasks:e.options?.maxConcurrentTasks??this.defaultMaxConcurrentTasks,metadata:e.options?.metadata};return new Ir(s)}createDefaultTeam(){let e=new Map,t=["coordinator","programmer","reviewer","tester"];for(let s of t)e.set(s,this.createFromRole(s));return e}createTeamForTask(e){let t=[],s=e.toLowerCase();return t.push(this.createFromRole("coordinator")),(s.includes("\u524D\u7AEF")||s.includes("ui")||s.includes("react"))&&t.push(this.createFromRole("frontend")),(s.includes("\u540E\u7AEF")||s.includes("api")||s.includes("backend"))&&t.push(this.createFromRole("backend")),(s.includes("\u5168\u6808")||s.includes("fullstack"))&&t.push(this.createFromRole("fullstack")),(s.includes("\u5B89\u5168")||s.includes("security")||s.includes("\u6F0F\u6D1E"))&&t.push(this.createFromRole("security")),(s.includes("\u6D4B\u8BD5")||s.includes("test"))&&t.push(this.createFromRole("tester")),(s.includes("\u90E8\u7F72")||s.includes("docker")||s.includes("ci"))&&t.push(this.createFromRole("devops")),(s.includes("\u67B6\u6784")||s.includes("\u8BBE\u8BA1")||s.includes("architecture"))&&t.push(this.createFromRole("architect")),(s.includes("\u6587\u6863")||s.includes("document"))&&t.push(this.createFromRole("documenter")),(s.includes("\u8C03\u8BD5")||s.includes("debug")||s.includes("bug"))&&t.push(this.createFromRole("debugger")),(s.includes("\u6570\u636E")||s.includes("data")||s.includes("\u5206\u6790"))&&t.push(this.createFromRole("data")),t.length===1&&t.push(this.createFromRole("programmer")),t.some(n=>n.role.name==="\u4EE3\u7801\u5BA1\u67E5\u5458")||t.push(this.createFromRole("reviewer")),t}static getPredefinedRoles(){return Object.values(fc)}static getRoleTemplate(e){return fc[e]}};function Am(a){return new yc(a)}var kC=[{id:"typescript",name:"TypeScript",description:"TypeScript \u7F16\u7A0B",level:5,tags:["languages","javascript"]},{id:"javascript",name:"JavaScript",description:"JavaScript \u7F16\u7A0B",level:5,tags:["languages"]},{id:"python",name:"Python",description:"Python \u7F16\u7A0B",level:5,tags:["languages"]},{id:"go",name:"Go",description:"Go \u7F16\u7A0B",level:4,tags:["languages"]},{id:"rust",name:"Rust",description:"Rust \u7F16\u7A0B",level:4,tags:["languages"]},{id:"java",name:"Java",description:"Java \u7F16\u7A0B",level:4,tags:["languages"]},{id:"react",name:"React",description:"React \u524D\u7AEF\u5F00\u53D1",level:5,tags:["frameworks","frontend"]},{id:"vue",name:"Vue",description:"Vue \u524D\u7AEF\u5F00\u53D1",level:4,tags:["frameworks","frontend"]},{id:"nodejs",name:"Node.js",description:"Node.js \u540E\u7AEF\u5F00\u53D1",level:5,tags:["frameworks","backend"]},{id:"express",name:"Express",description:"Express Web \u6846\u67B6",level:4,tags:["frameworks","backend"]},{id:"nextjs",name:"Next.js",description:"Next.js \u5168\u6808\u6846\u67B6",level:4,tags:["frameworks","fullstack"]},{id:"coding",name:"\u7F16\u7A0B\u5B9E\u73B0",description:"\u4EE3\u7801\u7F16\u5199\u548C\u5B9E\u73B0",level:5,tags:["skills","core"]},{id:"debugging",name:"\u8C03\u8BD5",description:"\u95EE\u9898\u8C03\u8BD5\u548C\u4FEE\u590D",level:4,tags:["skills","core"]},{id:"refactoring",name:"\u91CD\u6784",description:"\u4EE3\u7801\u91CD\u6784\u548C\u4F18\u5316",level:4,tags:["skills","core"]},{id:"testing",name:"\u6D4B\u8BD5",description:"\u7F16\u5199\u548C\u6267\u884C\u6D4B\u8BD5",level:4,tags:["skills","quality"]},{id:"review",name:"\u4EE3\u7801\u8BC4\u5BA1",description:"\u4EE3\u7801\u5BA1\u67E5\u548C\u53CD\u9988",level:4,tags:["skills","quality"]},{id:"documentation",name:"\u6587\u6863",description:"\u7F16\u5199\u6280\u672F\u6587\u6863",level:3,tags:["skills","communication"]},{id:"architecture",name:"\u67B6\u6784\u8BBE\u8BA1",description:"\u7CFB\u7EDF\u67B6\u6784\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"design",name:"\u8BBE\u8BA1",description:"\u8F6F\u4EF6\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"api-design",name:"API \u8BBE\u8BA1",description:"API \u63A5\u53E3\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"database-design",name:"\u6570\u636E\u5E93\u8BBE\u8BA1",description:"\u6570\u636E\u5E93\u67B6\u6784\u8BBE\u8BA1",level:4,tags:["skills","design"]},{id:"git",name:"Git",description:"Git \u7248\u672C\u63A7\u5236",level:5,tags:["tools","vcs"]},{id:"docker",name:"Docker",description:"Docker \u5BB9\u5668\u5316",level:4,tags:["tools","devops"]},{id:"ci-cd",name:"CI/CD",description:"\u6301\u7EED\u96C6\u6210\u548C\u90E8\u7F72",level:4,tags:["tools","devops"]},{id:"shell",name:"Shell",description:"Shell \u811A\u672C\u7F16\u5199",level:4,tags:["tools","scripting"]},{id:"security",name:"\u5B89\u5168",description:"\u5B89\u5168\u5F00\u53D1\u5B9E\u8DF5",level:4,tags:["domains","security"]},{id:"performance",name:"\u6027\u80FD\u4F18\u5316",description:"\u6027\u80FD\u5206\u6790\u548C\u4F18\u5316",level:4,tags:["domains","optimization"]},{id:"frontend",name:"\u524D\u7AEF\u5F00\u53D1",description:"\u524D\u7AEF\u5F00\u53D1\u7EFC\u5408",level:5,tags:["domains","web"]},{id:"backend",name:"\u540E\u7AEF\u5F00\u53D1",description:"\u540E\u7AEF\u5F00\u53D1\u7EFC\u5408",level:5,tags:["domains","web"]},{id:"fullstack",name:"\u5168\u6808\u5F00\u53D1",description:"\u5168\u6808\u5F00\u53D1\u7EFC\u5408",level:4,tags:["domains","web"]},{id:"devops",name:"DevOps",description:"DevOps \u5B9E\u8DF5",level:4,tags:["domains","operations"]},{id:"ai-ml",name:"AI/ML",description:"\u4EBA\u5DE5\u667A\u80FD\u548C\u673A\u5668\u5B66\u4E60",level:3,tags:["domains","ai"]}],bc=class{capabilities=new Map;constructor(){for(let e of kC)this.capabilities.set(e.id,e);}getCapability(e){return this.capabilities.get(e)}registerCapability(e){this.capabilities.set(e.id,e);}listCapabilities(){return Array.from(this.capabilities.values())}listByCategory(e){return Array.from(this.capabilities.values()).filter(t=>t.tags.includes(e))}calculateMatch(e,t){if(e.length===0||t.includes("*"))return 1;let s=0,n=0;for(let o of e)if(t.includes(o)){s++;let l=this.capabilities.get(o);n+=l?l.level/5:.8;}else {let l=this.capabilities.get(o);if(l)for(let c of t){let u=this.capabilities.get(c);if(u&&this.hasCommonTag(l,u)){s+=.5,n+=.5*(u.level/5);break}}}let r=s/e.length,i=s>0?n/s:0;return r*.7+i*.3}hasCommonTag(e,t){return e.tags.some(s=>t.tags.includes(s))}inferCapabilities(e){let t=[],s=e.toLowerCase(),n={typescript:["typescript","ts",".ts"],javascript:["javascript","js",".js"],python:["python","py",".py"],react:["react","jsx","tsx","component"],nodejs:["node","express","backend"],testing:["test","jest","mocha","spec"],debugging:["debug","fix","bug","error"],refactoring:["refactor","optimize","improve"],documentation:["document","readme","docs"],security:["security","auth","encrypt","password"],database:["database","sql","mongodb","redis"],api:["api","rest","graphql","endpoint"]};for(let[r,i]of Object.entries(n))i.some(o=>s.includes(o))&&t.push(r);return t.length===0&&t.push("coding"),t}},Em=new bc;var Bo=class extends EventEmitter{agents=new Map;agentInstances=new Map;config;healthCheckTimer;started=false;constructor(e){super(),this.config={heartbeatTimeout:e?.heartbeatTimeout??9e4,healthCheckInterval:e?.healthCheckInterval??3e4,maxAgents:e?.maxAgents??100,autoCleanup:e?.autoCleanup??true};}start(){this.started||(this.started=true,this.config.autoCleanup&&this.startHealthCheck(),this.emit("started"));}stop(){this.started&&(this.started=false,this.stopHealthCheck(),this.emit("stopped"));}register(e){if(this.agents.size>=this.config.maxAgents)throw new Error(`Registry full: max ${this.config.maxAgents} agents`);let t=e.getRegistration();if(this.agents.has(t.id))throw new Error(`Agent already registered: ${t.id}`);return this.agents.set(t.id,t),this.agentInstances.set(t.id,e),this.setupAgentListeners(e),this.emit("agent_registered",{agentId:t.id,registration:t,timestamp:Date.now()}),t}registerMany(e){return e.map(t=>this.register(t))}unregister(e,t){if(!this.agents.get(e))return false;let n=this.agentInstances.get(e);return n&&(n.removeAllListeners(),n.stop()),this.agents.delete(e),this.agentInstances.delete(e),this.emit("agent_unregistered",{agentId:e,reason:t??"manual",timestamp:Date.now()}),true}updateStatus(e,t,s){let n=this.agents.get(e);if(!n)return;let r=n.status;n.status=t,this.emit("agent_status_changed",{agentId:e,previousStatus:r,newStatus:t,reason:s,timestamp:Date.now()});}handleHeartbeat(e){let t=this.agents.get(e.agentId);t&&(t.lastHeartbeat=e.timestamp,t.status=e.status,t.availability=e.availability,this.emit("agent_heartbeat",{...e,timestamp:Date.now()}));}get(e){return this.agents.get(e)}getInstance(e){return this.agentInstances.get(e)}getAll(){return Array.from(this.agents.values())}listAll(){return this.getAll()}getActive(){return this.getAll().filter(e=>e.status==="active"||e.status==="busy")}query(e){let t=this.getAll();if(e.status){let i=Array.isArray(e.status)?e.status:[e.status];t=t.filter(o=>i.includes(o.status));}e.minAvailability!==void 0&&(t=t.filter(i=>i.availability>=e.minAvailability)),e.minReputation!==void 0&&(t=t.filter(i=>i.reputation>=e.minReputation));let s=t.map(i=>{let o=this.calculateMatchDetails(i,e);return {agent:i,score:this.calculateOverallScore(o),details:o}}),n=e.requiredCapabilities?.length?s.filter(i=>i.details.capabilityMatch>=.5):s,r=e.sortBy??"match";return n.sort((i,o)=>{switch(r){case "availability":return o.agent.availability-i.agent.availability;case "reputation":return o.agent.reputation-i.agent.reputation;case "priority":return (i.agent.role.priority??1)-(o.agent.role.priority??1);default:return o.score-i.score}}),e.limit?n.slice(0,e.limit):n}findBestMatch(e){let t=this.query({status:["active","busy"],requiredCapabilities:e,minAvailability:.1,sortBy:"match",limit:1});if(t[0])return t[0];let s=this.getActive();if(s.length>0){s.sort((r,i)=>{let o=r.reputation*.6+r.availability*.4;return i.reputation*.6+i.availability*.4-o});let n=s[0];return {agent:n,score:.5,details:{capabilityMatch:.5,availabilityScore:n.availability,reputationScore:n.reputation/5,specializationBonus:0}}}}findMatches(e,t){let s=this.query({status:["active","busy"],requiredCapabilities:e,minAvailability:.1,sortBy:"match",limit:t});if(s.length>=t)return s;let n=t-s.length,r=new Set(s.map(o=>o.agent.id)),i=this.getActive().filter(o=>!r.has(o.id)).slice(0,n);for(let o of i)s.push({agent:o,score:.5,details:{capabilityMatch:.5,availabilityScore:o.availability,reputationScore:o.reputation/5,specializationBonus:0}});return s}groupByCapability(){let e=new Map;for(let t of this.agents.values())for(let s of t.capabilities)e.has(s)||e.set(s,[]),e.get(s).push(t);return e}getStats(){let e=this.getAll(),t={total:e.length,active:0,busy:0,paused:0,offline:0,avgAvailability:0,avgReputation:0},s=0,n=0;for(let r of e){switch(r.status){case "active":t.active++;break;case "busy":t.busy++;break;case "paused":t.paused++;break;case "offline":t.offline++;break}s+=r.availability,n+=r.reputation;}return e.length>0&&(t.avgAvailability=s/e.length,t.avgReputation=n/e.length),t}calculateMatchDetails(e,t){let s=t.requiredCapabilities?.length?Em.calculateMatch(t.requiredCapabilities,e.capabilities):1,n=e.availability,r=e.reputation/5,i=0;return t.specializations?.length&&e.specializations.length&&(i=t.specializations.filter(l=>e.specializations.includes(l)).length/t.specializations.length*.2),{capabilityMatch:s,availabilityScore:n,reputationScore:r,specializationBonus:i}}calculateOverallScore(e){return e.capabilityMatch*.4+e.availabilityScore*.25+e.reputationScore*.25+e.specializationBonus}setupAgentListeners(e){e.on("heartbeat",t=>{this.handleHeartbeat(t);}),e.on("status_changed",t=>{this.updateStatus(t.agentId,t.newStatus);});}startHealthCheck(){this.healthCheckTimer=setInterval(()=>{this.performHealthCheck();},this.config.healthCheckInterval);}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=void 0);}performHealthCheck(){let e=Date.now(),t=[];for(let[s,n]of this.agents)e-n.lastHeartbeat>this.config.heartbeatTimeout&&(t.push(s),this.emit("agent_timeout",{agentId:s,lastHeartbeat:n.lastHeartbeat,timeout:this.config.heartbeatTimeout,timestamp:e}));if(this.config.autoCleanup&&t.length>0){for(let s of t)this.unregister(s,"heartbeat_timeout");this.emit("cleanup_performed",{removedAgents:t,timestamp:e});}}clear(){let e=Array.from(this.agents.keys());for(let t of e)this.unregister(t,"registry_cleared");}get size(){return this.agents.size}};function Im(a){return new Bo(a)}new Bo;var Go=class extends EventEmitter{subscribers=new Map;messageHistory=[];messageQueue=[];config;stats={sent:0,received:0,processed:0,failed:0,byType:new Map,avgProcessingTime:0};processing=false;messageCounter=0;constructor(e){super(),this.config={maxQueueSize:e?.maxQueueSize??1e3,defaultTTL:e?.defaultTTL??6e4,enablePersistence:e?.enablePersistence??false,enableReplay:e?.enableReplay??true,maxRetries:e?.maxRetries??3,retryDelay:e?.retryDelay??1e3};}async publish(e,t,s){let n={id:this.generateMessageId(),type:e,from:s?.from??"system",to:s?.to??"broadcast",payload:t,priority:s?.priority??"normal",createdAt:Date.now(),expiresAt:Date.now()+(s?.ttl??this.config.defaultTTL),correlationId:s?.correlationId,replyTo:s?.replyTo,metadata:s?.metadata};return this.enqueue(n),this.stats.sent++,this.incrementTypeStats(e),this.emit("message_published",n),await this.processQueue(),n}async publishTaskBroadcast(e){return this.publish("task_broadcast",e,{from:"coordinator",to:"broadcast",priority:e.priority,ttl:e.bidDeadline-Date.now(),correlationId:e.id})}async publishBid(e){return this.publish("bid",e,{from:e.agentId,to:"coordinator",priority:"high",correlationId:e.taskId})}async publishNegotiationMessage(e){return this.publish("negotiation",e,{from:e.from,to:e.to,priority:"high",correlationId:e.sessionId})}subscribe(e){return this.subscribers.set(e.id,e),this.emit("subscriber_added",{subscriberId:e.id,types:e.types}),()=>this.unsubscribe(e.id)}subscribeToType(e,t,s){return this.subscribe({id:e,types:[t],callback:s})}subscribeForAgent(e,t){return this.subscribe({id:`agent-${e}`,types:["task_broadcast","bid_evaluation","negotiation","execution_command","system"],callback:t,filter:s=>s.to===e||s.to==="broadcast"})}unsubscribe(e){let t=this.subscribers.delete(e);return t&&this.emit("subscriber_removed",{subscriberId:e}),t}async request(e,t,s){let n=s?.timeout??3e4,r=await this.publish(e,t,{from:s?.from,to:s?.to,priority:"high"});return new Promise((i,o)=>{let l=setTimeout(()=>{this.unsubscribe(`response-${r.id}`),o(new Error(`Request timeout: ${r.id}`));},n);this.subscribe({id:`response-${r.id}`,types:[e],callback:c=>{c.replyTo===r.id&&(clearTimeout(l),this.unsubscribe(`response-${r.id}`),i(c));}});})}async reply(e,t,s){return this.publish(e.type,t,{from:e.to==="broadcast"?"system":e.to,to:e.from,priority:s?.priority??e.priority,correlationId:e.correlationId,replyTo:e.id})}getHistory(e){let t=[...this.messageHistory];return e?.type&&(t=t.filter(s=>s.type===e.type)),e?.from&&(t=t.filter(s=>s.from===e.from)),e?.to&&(t=t.filter(s=>s.to===e.to||s.to==="broadcast")),e?.correlationId&&(t=t.filter(s=>s.correlationId===e.correlationId)),e?.since&&(t=t.filter(s=>s.createdAt>=e.since)),e?.limit&&(t=t.slice(-e.limit)),t}async replay(e,t){if(!this.config.enableReplay)throw new Error("Replay is not enabled");let s=t?.filter?e.filter(t.filter):e;for(let n of s)await this.deliverMessage(n),t?.delay&&await new Promise(r=>setTimeout(r,t.delay));}getStats(){return {...this.stats,byType:new Map(this.stats.byType)}}clearQueue(){this.messageQueue=[],this.emit("queue_cleared");}clearHistory(){this.messageHistory=[],this.emit("history_cleared");}resetStats(){this.stats={sent:0,received:0,processed:0,failed:0,byType:new Map,avgProcessingTime:0};}enqueue(e){if(this.messageQueue.length>=this.config.maxQueueSize){let r=this.messageQueue.findIndex(i=>i.priority==="low");r>=0?this.messageQueue.splice(r,1):this.messageQueue.shift();}let t={critical:0,high:1,medium:2,normal:3,low:4},s=t[e.priority]??3,n=this.messageQueue.length;for(let r=0;r<this.messageQueue.length;r++)if((t[this.messageQueue[r].priority]??3)>s){n=r;break}this.messageQueue.splice(n,0,e);}async processQueue(){if(!this.processing){this.processing=true;try{for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(e.expiresAt&&Date.now()>e.expiresAt){this.emit("message_expired",e);continue}await this.deliverMessage(e);}}finally{this.processing=false;}}}async deliverMessage(e){let t=Date.now();this.stats.received++,this.config.enableReplay&&(this.messageHistory.push(e),this.messageHistory.length>this.config.maxQueueSize*10&&(this.messageHistory=this.messageHistory.slice(-this.config.maxQueueSize*5)));let s=this.getMatchingSubscribers(e);s.sort((r,i)=>(r.priority??10)-(i.priority??10));for(let r of s)try{await r.callback(e),this.stats.processed++;}catch(i){this.stats.failed++,this.emit("delivery_error",{message:e,subscriberId:r.id,error:i});}let n=Date.now()-t;this.stats.avgProcessingTime=(this.stats.avgProcessingTime*(this.stats.received-1)+n)/this.stats.received,this.emit("message_delivered",{message:e,subscriberCount:s.length,processingTime:n});}getMatchingSubscribers(e){let t=[];for(let s of this.subscribers.values())s.types.includes(e.type)&&(s.filter&&!s.filter(e)||t.push(s));return t}generateMessageId(){return `msg-${Date.now()}-${++this.messageCounter}`}incrementTypeStats(e){let t=this.stats.byType.get(e)??0;this.stats.byType.set(e,t+1);}get subscriberCount(){return this.subscribers.size}get queueLength(){return this.messageQueue.length}};function Mm(a){return new Go(a)}new Go;W();var _C={capabilityMatch:.3,availability:.15,reputation:.2,confidence:.25,efficiency:.1},vc=class extends EventEmitter{registry;messageBus;config;weights;sessions=new Map;sessionCounter=0;constructor(e,t,s){super(),this.registry=e,this.messageBus=t,this.config={defaultTimeout:s?.defaultTimeout??3e4,minBids:s?.minBids??1,maxBids:s?.maxBids??10,selectCount:s?.selectCount??10,minAcceptScore:s?.minAcceptScore??25,parallelBidding:s?.parallelBidding??true,weights:s?.weights??_C},this.weights=this.config.weights,this.setupMessageSubscriptions();}async startBidding(e,t){let s=this.generateSessionId(),n=t?.timeout??this.config.defaultTimeout,r={id:s,task:e,bids:new Map,evaluations:new Map,status:"collecting",selectedAgents:[],createdAt:Date.now(),deadline:Date.now()+n};return this.sessions.set(s,r),this.emit("session_created",{sessionId:s,taskId:e.id,deadline:r.deadline}),t?.broadcast!==false&&await this.broadcastTask(e),this.waitForBids(r,{timeout:n,minBids:t?.minBids??this.config.minBids,selectCount:t?.selectCount??this.config.selectCount})}async requestBidsFromAgents(e,t,s){let n=this.generateSessionId(),r=s?.timeout??this.config.defaultTimeout,i={id:n,task:e,bids:new Map,evaluations:new Map,status:"collecting",selectedAgents:[],createdAt:Date.now(),deadline:Date.now()+r};this.sessions.set(n,i);let o=t.map(async l=>{let c=this.registry.getInstance(l);if(c)try{let u=await c.evaluateTask(e);s?.onAgentDecision?.({agentId:l,agentName:c.role.name,participate:u.participate,reason:u.reason,capabilityScore:u.capabilityScore,confidence:u.bid?.confidence}),this.emit("agent_bid_decision",{agentId:l,agentName:c.role.name,participate:u.participate,reason:u.reason,capabilityScore:u.capabilityScore,confidence:u.bid?.confidence}),u.participate&&u.bid&&await this.submitBid(n,u.bid);}catch(u){let d=u instanceof Error?u.message:String(u);s?.onAgentDecision?.({agentId:l,agentName:c.role.name,participate:false,reason:`\u8BC4\u4F30\u5931\u8D25: ${d}`}),this.emit("bid_request_failed",{agentId:l,error:u});}});if(this.config.parallelBidding)await Promise.all(o);else for(let l of o)await l;return this.finalizeBidding(i)}async submitBid(e,t){let s=this.sessions.get(e);return s?s.status!=="collecting"?(this.emit("bid_rejected",{bid:t,reason:"Session not collecting"}),false):Date.now()>s.deadline?(this.emit("bid_rejected",{bid:t,reason:"Deadline passed"}),false):s.bids.has(t.agentId)?(this.emit("bid_rejected",{bid:t,reason:"Already submitted"}),false):s.bids.size>=this.config.maxBids?(this.emit("bid_rejected",{bid:t,reason:"Max bids reached"}),false):(s.bids.set(t.agentId,t),this.emit("bid_received",{sessionId:e,bid:t,totalBids:s.bids.size}),true):(this.emit("bid_rejected",{bid:t,reason:"Session not found"}),false)}evaluateBid(e,t){let s=this.registry.get(e.agentId),n=this.calculateCapabilityMatch(t.requiredCapabilities,s?.capabilities??[]),r=s?.availability??0,i=(s?.reputation??3)/5,o=e.confidence,c=Math.min(1,3e5/Math.max(e.estimatedTime,1e3)),u=(n*this.weights.capabilityMatch+r*this.weights.availability+i*this.weights.reputation+o*this.weights.confidence+c*this.weights.efficiency)*100;return {bid:e,score:u,breakdown:{capabilityMatch:n*25,availabilityScore:r*25,reputationScore:i*25,confidenceScore:o*25,efficiencyScore:c*10},selected:false,rank:0}}evaluateAllBids(e){e.status="evaluating";let t=[];for(let s of e.bids.values()){let n=this.evaluateBid(s,e.task);t.push(n),e.evaluations.set(s.agentId,n);}return t.sort((s,n)=>n.score-s.score),t.forEach((s,n)=>{s.rank=n+1;}),this.emit("bids_evaluated",{sessionId:e.id,evaluations:t}),t}selectAgents(e,t,s){e.status="selecting";let n=t.filter(o=>o.score>=this.config.minAcceptScore);m.debug("BIDDING",`selectAgents: ${n.length}/${t.length} qualified (minScore=${this.config.minAcceptScore}, selectCount=${s})`);let r=n.slice(0,s);for(let o of r)o.selected=true;let i=r.map(o=>o.bid.agentId);return e.selectedAgents=i,this.emit("agents_selected",{sessionId:e.id,selectedAgents:i,evaluations:r}),i}cancelSession(e,t){let s=this.sessions.get(e);return s?(s.timer&&clearTimeout(s.timer),s.status="cancelled",s.completedAt=Date.now(),this.emit("session_cancelled",{sessionId:e,reason:t,bidsReceived:s.bids.size}),this.sessions.delete(e),true):false}getSession(e){return this.sessions.get(e)}get activeSessionCount(){return this.sessions.size}async broadcastTask(e){await this.messageBus.publishTaskBroadcast(e),this.emit("task_broadcasted",{taskId:e.id,requiredCapabilities:e.requiredCapabilities});}waitForBids(e,t){return new Promise(s=>{let n=()=>{e.bids.size>=this.config.maxBids&&(e.timer&&clearTimeout(e.timer),s(this.finalizeBidding(e,t.selectCount)));},r=i=>{i.sessionId===e.id&&n();};this.on("bid_received",r),e.timer=setTimeout(()=>{this.off("bid_received",r),e.bids.size<t.minBids?(e.status="timeout",e.completedAt=Date.now(),s({sessionId:e.id,taskId:e.task.id,success:false,selectedAgents:[],bids:Array.from(e.bids.values()),evaluations:[],failureReason:`Insufficient bids: ${e.bids.size}/${t.minBids}`,duration:Date.now()-e.createdAt}),this.sessions.delete(e.id)):s(this.finalizeBidding(e,t.selectCount));},t.timeout);})}finalizeBidding(e,t){let s=this.evaluateAllBids(e),n=t??this.config.selectCount,r=this.selectAgents(e,s,n);e.status="completed",e.completedAt=Date.now();let i={sessionId:e.id,taskId:e.task.id,success:r.length>0,selectedAgents:r,bids:Array.from(e.bids.values()),evaluations:s,duration:e.completedAt-e.createdAt};return r.length===0&&(i.failureReason="No qualified agents"),this.emit("bidding_completed",i),this.sessions.delete(e.id),i}calculateCapabilityMatch(e,t){if(e.length===0||t.includes("*"))return 1;let s=0;for(let n of e)t.includes(n)&&s++;return s/e.length}setupMessageSubscriptions(){this.messageBus.subscribeToType("bidding_engine","bid",async e=>{let t=e.payload;for(let s of this.sessions.values())if(s.task.id===t.taskId){await this.submitBid(s.id,t);break}});}generateSessionId(){return `bidding-${Date.now()}-${++this.sessionCounter}`}setWeights(e){this.weights={...this.weights,...e};}};function Pm(a,e,t){return new vc(a,e,t)}var AC={maxRounds:5,roundTimeout:6e4,consensusThreshold:.7,minParticipants:2,allowLateJoin:false,autoGenerateProposal:true},wc=class extends EventEmitter{registry;messageBus;config;sessions=new Map;sessionCounter=0;constructor(e,t,s){super(),this.registry=e,this.messageBus=t,this.config={...AC,...s},this.setupMessageSubscriptions();}setLlmCall(e){this.config.llmCall=e;}async startNegotiation(e,t,s,n){if(t.length<this.config.minParticipants)throw new Error(`Insufficient participants: ${t.length}/${this.config.minParticipants}`);let r=this.generateSessionId(),i=Date.now(),o={id:r,taskId:e.id,taskDescription:e.description??e.userRequest,participants:t,status:"active",currentRound:0,maxRounds:this.config.maxRounds,proposals:[],messages:[],votes:new Map,consensusThreshold:this.config.consensusThreshold,createdAt:i,config:{maxRounds:this.config.maxRounds,roundTimeout:this.config.roundTimeout,consensusThreshold:this.config.consensusThreshold,minParticipants:this.config.minParticipants,allowLateJoin:this.config.allowLateJoin}};this.sessions.set(r,o),this.emit("negotiation_started",{sessionId:r,taskId:e.id,participants:t});let l=n?.initialProposal;return !l&&this.config.autoGenerateProposal&&(l=await this.generateProposal(o,e,s)),l&&(o.proposals.push(l),o.currentProposal=l,this.emit("proposal_submitted",{sessionId:r,proposal:l})),o}async conductRound(e){let t=this.sessions.get(e);if(!t)throw new Error(`Session not found: ${e}`);t.currentRound++,this.emit("round_started",{sessionId:e,round:t.currentRound});let s=[];for(let i of t.participants){let o=this.registry.getInstance(i);if(!(!o||!t.currentProposal))try{let l=await o.participateInNegotiation(e,t.currentProposal,{taskDescription:t.taskDescription??t.taskId,otherParticipants:t.participants});l.round=t.currentRound,s.push(l),t.messages.push(l),this.emit("message_received",{sessionId:e,message:l});}catch(l){this.emit("participant_error",{sessionId:e,participantId:i,error:l});}}let n=this.analyzeRoundMessages(s);if(n.hasConcerns&&t.currentProposal&&this.config.llmCall){let i=await this.refineProposal(t,t.currentProposal,n.concerns,n.suggestions);i&&(t.currentProposal=i,t.proposals.push(i),this.emit("proposal_updated",{sessionId:e,proposal:i}));}let r=this.checkConsensus(s);return this.emit("round_completed",{sessionId:e,round:t.currentRound,messageCount:s.length,consensusReached:r}),{round:t.currentRound,messages:s,consensusReached:r}}async startVoting(e){let t=this.sessions.get(e);if(!t||!t.currentProposal)throw new Error(`Session or proposal not found: ${e}`);this.emit("voting_started",{sessionId:e,proposalId:t.currentProposal.id});let s=new Map;for(let r of t.participants){let i=t.messages.filter(o=>o.from===r).pop();i?.data?.vote?s.set(r,i.data.vote):s.set(r,"abstain"),this.emit("vote_cast",{sessionId:e,agentId:r,vote:s.get(r)});}t.votes=s;let n=this.calculateVotingResult(t,s);return this.emit("voting_completed",{sessionId:e,result:n}),n}async runFullNegotiation(e,t,s){let n=Date.now(),r=await this.startNegotiation(e,t,s),i=false;for(;r.currentRound<r.maxRounds&&!i&&(i=(await this.conductRound(r.id)).consensusReached,!i);)await new Promise(d=>setTimeout(d,1e3));let o=await this.startVoting(r.id);o.approved?(r.status="completed",r.consensusProposal=r.currentProposal,this.emit("consensus_reached",{sessionId:r.id,proposal:r.currentProposal})):(r.status="failed",this.emit("negotiation_failed",{sessionId:r.id,reason:"Voting rejected",rounds:r.currentRound})),r.completedAt=Date.now();let l=r,c=r.messages.length;return this.sessions.delete(r.id),{success:o.approved,proposal:o.approved?r.currentProposal:void 0,result:o,rounds:r.currentRound,duration:Date.now()-n,session:l,messageCount:c}}async generateProposal(e,t,s){let n=`proposal-${e.id}-${e.proposals.length+1}`,r=[],i=[[]];for(let l=0;l<s.length;l++){let c=s[l],u=`subtask-${l+1}`;r.push({id:u,description:`\u5B50\u4EFB\u52A1 ${l+1}: ${c.proposedApproach}`,assignedAgent:c.agentId,estimatedTime:c.estimatedTime,estimatedTokens:c.resourceRequirements.estimatedTokens,dependencies:l>0?[`subtask-${l}`]:[],priority:1}),r[l].dependencies.length===0?i[0].push(u):(i[1]||(i[1]=[]),i[1].push(u));}return {id:n,sessionId:e.id,proposer:"system",version:1,subtasks:r,executionLevels:i,estimatedTotalTime:r.reduce((l,c)=>l+c.estimatedTime,0),estimatedTotalTokens:r.reduce((l,c)=>l+c.estimatedTokens,0),risks:[],createdAt:Date.now()}}async refineProposal(e,t,s,n){if(!this.config.llmCall)return null;let r=`
3103
3103
  \u5F53\u524D\u63D0\u6848\uFF1A
3104
3104
  ${JSON.stringify(t,null,2)}
3105
3105
 
@@ -3112,7 +3112,7 @@ ${n.map((i,o)=>`${o+1}. ${i}`).join(`
3112
3112
  `)}
3113
3113
 
3114
3114
  \u8BF7\u6839\u636E\u53CD\u9988\u4F18\u5316\u63D0\u6848\u3002\u8F93\u51FA JSON \u683C\u5F0F\u7684\u65B0\u63D0\u6848\u3002
3115
- `;try{let o=(await this.config.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u5206\u914D\u4E13\u5BB6\uFF0C\u8D1F\u8D23\u4F18\u5316\u591A Agent \u534F\u4F5C\u7684\u6267\u884C\u63D0\u6848\u3002",r,{onText:this.config.onText?l=>this.config.onText(l,"negotiation"):void 0})).match(/\{[\s\S]*\}/);if(o){let l=JSON.parse(o[0]);return l.id=`${t.id}-v${t.version+1}`,l.version=t.version+1,l.createdAt=Date.now(),l}}catch(i){this.emit("proposal_refinement_failed",{sessionId:e.id,error:i});}return null}analyzeRoundMessages(e){let t=[],s=[],n=0,r=0;for(let i of e)i.type==="concern"||i.type==="counter"?(r++,i.data?.concerns&&t.push(...i.data.concerns)):i.type==="support"&&n++,i.data?.suggestions&&s.push(...i.data.suggestions);return {hasConcerns:t.length>0||r>n,concerns:t,suggestions:s,supportCount:n,oppositionCount:r}}checkConsensus(e){let t=e.filter(n=>n.data?.vote).map(n=>n.data?.vote);return t.length===0?false:t.filter(n=>n==="approve").length/t.length>=this.config.consensusThreshold}calculateVotingResult(e,t){let s=0,n=0,r=0;for(let c of t.values())switch(c){case "approve":s++;break;case "reject":n++;break;case "abstain":r++;break}let i=s+n,o=i>0?s/i:0,l=o>=e.consensusThreshold;return {proposalId:e.currentProposal?.id??"",approved:l,approveCount:s,rejectCount:n,abstainCount:r,approvalRate:o,votedAt:Date.now()}}setupMessageSubscriptions(){this.messageBus.subscribeToType("negotiation_engine","negotiation",async e=>{let t=e.payload,s=this.sessions.get(t.sessionId);s&&(s.messages.push(t),this.emit("message_received",{sessionId:t.sessionId,message:t}));});}generateSessionId(){return `negotiation-${Date.now()}-${++this.sessionCounter}`}getSession(e){return this.sessions.get(e)}setOnText(e){this.config.onText=e;}cancelNegotiation(e,t){let s=this.sessions.get(e);return s?(s.status="failed",s.completedAt=Date.now(),this.emit("negotiation_cancelled",{sessionId:e,reason:t}),this.sessions.delete(e),true):false}get activeSessionCount(){return this.sessions.size}};function Dm(a,e,t){return new wc(a,e,t)}var EC={strategy:"majority",conflictResolution:"coordinator_decides",threshold:.7,maxIterations:5,autoResolveConflicts:true},Cc=class extends EventEmitter{config;states=new Map;constructor(e){super(),this.config={...EC,...e};}initialize(e,t,s){let n=new Map;for(let[i,o]of s)n.set(i,{agentId:i,stance:"neutral",supportLevel:.5,concerns:[],weight:o,lastUpdated:Date.now()});let r={sessionId:e,proposal:t,attitudes:n,conflicts:[],progress:0,consensusReached:false};return this.states.set(e,r),this.emit("consensus_initialized",{sessionId:e,participantCount:n.size}),r}updateAttitude(e,t,s){let n=this.states.get(e);if(!n)return;let r=n.attitudes.get(t);r&&(Object.assign(r,s,{lastUpdated:Date.now()}),this.calculateProgress(n),this.emit("attitude_updated",{sessionId:e,agentId:t,attitude:r}));}extractAttitudeFromMessage(e,t){if(!this.states.get(e))return;let n="neutral",r=.5,i=[],o=[];switch(t.type){case "support":n="support",r=.9;break;case "concern":n="conditional",r=.4,t.data?.concerns&&i.push(...t.data.concerns);break;case "counter":n="oppose",r=.2,t.data?.concerns&&i.push(...t.data.concerns);break;case "question":n="neutral",r=.5;break}if(t.data?.vote)switch(t.data.vote){case "approve":n="support",r=1;break;case "reject":n="oppose",r=0;break;case "abstain":n="neutral",r=.5;break}this.updateAttitude(e,t.from,{stance:n,supportLevel:r,concerns:i,conditions:o.length>0?o:void 0});}identifyConflicts(e){let t=this.states.get(e);if(!t)return [];let s=[],n=[];for(let[r,i]of t.attitudes)(i.stance==="oppose"||i.supportLevel<.3)&&n.push(r);if(n.length>0){let r=[];for(let o of n){let l=t.attitudes.get(o);l?.concerns&&r.push(...l.concerns);}let i=[...new Set(r)];for(let o=0;o<i.length;o++){let l={id:`conflict-${e}-${o+1}`,type:"approach",description:i[o],parties:n,positions:new Map,severity:n.length>=2?3:2,resolved:false};for(let c of n)l.positions.set(c,"oppose");s.push(l);}}return t.conflicts=s,this.emit("conflicts_identified",{sessionId:e,conflictCount:s.length,conflicts:s}),s}async resolveConflict(e,t,s){let n=this.states.get(e);if(!n)return false;let r=n.conflicts.find(i=>i.id===t);return r?(r.resolved=true,r.resolution=s,this.emit("conflict_resolved",{sessionId:e,conflictId:t,resolution:s}),this.calculateProgress(n),true):false}applyConsensusStrategy(e){let t=this.states.get(e);if(!t)return {consensusReached:false,supportRatio:0,decision:"rejected"};let s=Array.from(t.attitudes.values()),n=0,r=false,i="needs_more_discussion";switch(this.config.strategy){case "majority":n=this.calculateMajoritySupport(s),r=n>=this.config.threshold,i=r?"approved":n<.3?"rejected":"needs_more_discussion";break;case "unanimous":let o=s.every(c=>c.stance==="support");n=o?1:0,r=o,i=o?"approved":"needs_more_discussion";break;case "weighted":n=this.calculateWeightedSupport(s),r=n>=this.config.threshold,i=r?"approved":n<.3?"rejected":"needs_more_discussion";break;case "supermajority":n=this.calculateMajoritySupport(s),r=n>=.67,i=r?"approved":"needs_more_discussion";break;case "approval":let l=s.filter(c=>c.stance==="support").length;n=l/s.length,r=l>=Math.ceil(s.length/2),i=r?"approved":"needs_more_discussion";break}return t.consensusReached=r,this.emit("consensus_evaluated",{sessionId:e,strategy:this.config.strategy,supportRatio:n,consensusReached:r,decision:i}),{consensusReached:r,supportRatio:n,decision:i}}generateFinalDecision(e,t){let s=this.states.get(e);if(!s)throw new Error(`State not found: ${e}`);let n;if(t)n={...t,proposal:t.type==="approved"?s.proposal:void 0,decidedAt:Date.now()};else {let{consensusReached:r,supportRatio:i}=this.applyConsensusStrategy(e),o=[];for(let[l,c]of s.attitudes)c.stance==="oppose"&&o.push({agentId:l,reason:c.concerns.join("; ")||"No specific reason"});n={type:r?"approved":i<.3?"rejected":"deferred",proposal:r?s.proposal:void 0,rationale:r?`\u5171\u8BC6\u8FBE\u6210 (\u652F\u6301\u7387: ${(i*100).toFixed(1)}%)`:`\u672A\u8FBE\u6210\u5171\u8BC6 (\u652F\u6301\u7387: ${(i*100).toFixed(1)}%)`,decidedBy:"consensus",decidedAt:Date.now(),dissent:o.length>0?o:void 0};}return s.finalDecision=n,this.emit("final_decision",{sessionId:e,decision:n}),n}getState(e){return this.states.get(e)}cleanup(e){this.states.delete(e);}calculateProgress(e){let t=Array.from(e.attitudes.values()),s=t.length,n=t.filter(c=>c.stance!=="neutral").length,r=e.conflicts.filter(c=>c.resolved).length,i=e.conflicts.length,o=n/s,l=i>0?r/i:1;e.progress=o*.5+l*.5;}calculateMajoritySupport(e){return e.filter(s=>s.stance==="support"||s.supportLevel>=.7).length/e.length}calculateWeightedSupport(e){let t=0,s=0;for(let n of e)t+=n.weight,s+=n.weight*n.supportLevel;return t>0?s/t:0}};function Lm(a){return new Cc(a)}W();var Om={maxSubtasks:10,maxParallelism:5},MC=`## \u4F60\u7684\u4EFB\u52A1
3115
+ `;try{let o=(await this.config.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u5206\u914D\u4E13\u5BB6\uFF0C\u8D1F\u8D23\u4F18\u5316\u591A Agent \u534F\u4F5C\u7684\u6267\u884C\u63D0\u6848\u3002",r,{onText:this.config.onText?l=>this.config.onText(l,"negotiation"):void 0})).match(/\{[\s\S]*\}/);if(o){let l=JSON.parse(o[0]);return l.id=`${t.id}-v${t.version+1}`,l.version=t.version+1,l.createdAt=Date.now(),l}}catch(i){this.emit("proposal_refinement_failed",{sessionId:e.id,error:i});}return null}analyzeRoundMessages(e){let t=[],s=[],n=0,r=0;for(let i of e)i.type==="concern"||i.type==="counter"?(r++,i.data?.concerns&&t.push(...i.data.concerns)):i.type==="support"&&n++,i.data?.suggestions&&s.push(...i.data.suggestions);return {hasConcerns:t.length>0||r>n,concerns:t,suggestions:s,supportCount:n,oppositionCount:r}}checkConsensus(e){let t=e.filter(n=>n.data?.vote).map(n=>n.data?.vote);return t.length===0?false:t.filter(n=>n==="approve").length/t.length>=this.config.consensusThreshold}calculateVotingResult(e,t){let s=0,n=0,r=0;for(let c of t.values())switch(c){case "approve":s++;break;case "reject":n++;break;case "abstain":r++;break}let i=s+n,o=i>0?s/i:0,l=o>=e.consensusThreshold;return {proposalId:e.currentProposal?.id??"",approved:l,approveCount:s,rejectCount:n,abstainCount:r,approvalRate:o,votedAt:Date.now()}}setupMessageSubscriptions(){this.messageBus.subscribeToType("negotiation_engine","negotiation",async e=>{let t=e.payload,s=this.sessions.get(t.sessionId);s&&(s.messages.push(t),this.emit("message_received",{sessionId:t.sessionId,message:t}));});}generateSessionId(){return `negotiation-${Date.now()}-${++this.sessionCounter}`}getSession(e){return this.sessions.get(e)}setOnText(e){this.config.onText=e;}cancelNegotiation(e,t){let s=this.sessions.get(e);return s?(s.status="failed",s.completedAt=Date.now(),this.emit("negotiation_cancelled",{sessionId:e,reason:t}),this.sessions.delete(e),true):false}get activeSessionCount(){return this.sessions.size}};function Dm(a,e,t){return new wc(a,e,t)}var IC={strategy:"majority",conflictResolution:"coordinator_decides",threshold:.7,maxIterations:5,autoResolveConflicts:true},Cc=class extends EventEmitter{config;states=new Map;constructor(e){super(),this.config={...IC,...e};}initialize(e,t,s){let n=new Map;for(let[i,o]of s)n.set(i,{agentId:i,stance:"neutral",supportLevel:.5,concerns:[],weight:o,lastUpdated:Date.now()});let r={sessionId:e,proposal:t,attitudes:n,conflicts:[],progress:0,consensusReached:false};return this.states.set(e,r),this.emit("consensus_initialized",{sessionId:e,participantCount:n.size}),r}updateAttitude(e,t,s){let n=this.states.get(e);if(!n)return;let r=n.attitudes.get(t);r&&(Object.assign(r,s,{lastUpdated:Date.now()}),this.calculateProgress(n),this.emit("attitude_updated",{sessionId:e,agentId:t,attitude:r}));}extractAttitudeFromMessage(e,t){if(!this.states.get(e))return;let n="neutral",r=.5,i=[],o=[];switch(t.type){case "support":n="support",r=.9;break;case "concern":n="conditional",r=.4,t.data?.concerns&&i.push(...t.data.concerns);break;case "counter":n="oppose",r=.2,t.data?.concerns&&i.push(...t.data.concerns);break;case "question":n="neutral",r=.5;break}if(t.data?.vote)switch(t.data.vote){case "approve":n="support",r=1;break;case "reject":n="oppose",r=0;break;case "abstain":n="neutral",r=.5;break}this.updateAttitude(e,t.from,{stance:n,supportLevel:r,concerns:i,conditions:o.length>0?o:void 0});}identifyConflicts(e){let t=this.states.get(e);if(!t)return [];let s=[],n=[];for(let[r,i]of t.attitudes)(i.stance==="oppose"||i.supportLevel<.3)&&n.push(r);if(n.length>0){let r=[];for(let o of n){let l=t.attitudes.get(o);l?.concerns&&r.push(...l.concerns);}let i=[...new Set(r)];for(let o=0;o<i.length;o++){let l={id:`conflict-${e}-${o+1}`,type:"approach",description:i[o],parties:n,positions:new Map,severity:n.length>=2?3:2,resolved:false};for(let c of n)l.positions.set(c,"oppose");s.push(l);}}return t.conflicts=s,this.emit("conflicts_identified",{sessionId:e,conflictCount:s.length,conflicts:s}),s}async resolveConflict(e,t,s){let n=this.states.get(e);if(!n)return false;let r=n.conflicts.find(i=>i.id===t);return r?(r.resolved=true,r.resolution=s,this.emit("conflict_resolved",{sessionId:e,conflictId:t,resolution:s}),this.calculateProgress(n),true):false}applyConsensusStrategy(e){let t=this.states.get(e);if(!t)return {consensusReached:false,supportRatio:0,decision:"rejected"};let s=Array.from(t.attitudes.values()),n=0,r=false,i="needs_more_discussion";switch(this.config.strategy){case "majority":n=this.calculateMajoritySupport(s),r=n>=this.config.threshold,i=r?"approved":n<.3?"rejected":"needs_more_discussion";break;case "unanimous":let o=s.every(c=>c.stance==="support");n=o?1:0,r=o,i=o?"approved":"needs_more_discussion";break;case "weighted":n=this.calculateWeightedSupport(s),r=n>=this.config.threshold,i=r?"approved":n<.3?"rejected":"needs_more_discussion";break;case "supermajority":n=this.calculateMajoritySupport(s),r=n>=.67,i=r?"approved":"needs_more_discussion";break;case "approval":let l=s.filter(c=>c.stance==="support").length;n=l/s.length,r=l>=Math.ceil(s.length/2),i=r?"approved":"needs_more_discussion";break}return t.consensusReached=r,this.emit("consensus_evaluated",{sessionId:e,strategy:this.config.strategy,supportRatio:n,consensusReached:r,decision:i}),{consensusReached:r,supportRatio:n,decision:i}}generateFinalDecision(e,t){let s=this.states.get(e);if(!s)throw new Error(`State not found: ${e}`);let n;if(t)n={...t,proposal:t.type==="approved"?s.proposal:void 0,decidedAt:Date.now()};else {let{consensusReached:r,supportRatio:i}=this.applyConsensusStrategy(e),o=[];for(let[l,c]of s.attitudes)c.stance==="oppose"&&o.push({agentId:l,reason:c.concerns.join("; ")||"No specific reason"});n={type:r?"approved":i<.3?"rejected":"deferred",proposal:r?s.proposal:void 0,rationale:r?`\u5171\u8BC6\u8FBE\u6210 (\u652F\u6301\u7387: ${(i*100).toFixed(1)}%)`:`\u672A\u8FBE\u6210\u5171\u8BC6 (\u652F\u6301\u7387: ${(i*100).toFixed(1)}%)`,decidedBy:"consensus",decidedAt:Date.now(),dissent:o.length>0?o:void 0};}return s.finalDecision=n,this.emit("final_decision",{sessionId:e,decision:n}),n}getState(e){return this.states.get(e)}cleanup(e){this.states.delete(e);}calculateProgress(e){let t=Array.from(e.attitudes.values()),s=t.length,n=t.filter(c=>c.stance!=="neutral").length,r=e.conflicts.filter(c=>c.resolved).length,i=e.conflicts.length,o=n/s,l=i>0?r/i:1;e.progress=o*.5+l*.5;}calculateMajoritySupport(e){return e.filter(s=>s.stance==="support"||s.supportLevel>=.7).length/e.length}calculateWeightedSupport(e){let t=0,s=0;for(let n of e)t+=n.weight,s+=n.weight*n.supportLevel;return t>0?s/t:0}};function Lm(a){return new Cc(a)}W();var Om={maxSubtasks:10,maxParallelism:5},PC=`## \u4F60\u7684\u4EFB\u52A1
3116
3116
  \u5206\u6790\u7528\u6237\u8BF7\u6C42\uFF0C\u5C06\u5176\u5206\u89E3\u4E3A\u53EF\u6267\u884C\u7684\u5B50\u4EFB\u52A1\u3002
3117
3117
 
3118
3118
  ## \u7528\u6237\u8BF7\u6C42
@@ -3157,9 +3157,9 @@ ${n.map((i,o)=>`${o+1}. ${i}`).join(`
3157
3157
  2. \u660E\u786E\u5B50\u4EFB\u52A1\u7684\u8F93\u5165\u8F93\u51FA
3158
3158
  3. \u8BC6\u522B\u53EF\u5E76\u884C\u7684\u4EFB\u52A1\u653E\u5728\u540C\u4E00\u7EC4
3159
3159
  4. \u6709\u4F9D\u8D56\u5173\u7CFB\u7684\u4EFB\u52A1\u4E32\u884C\u6267\u884C
3160
- 5. \u6BCF\u4E2A\u5B50\u4EFB\u52A1\u5BF9\u5E94\u4E00\u4E2A\u89D2\u8272`,PC=[{id:"programmer",name:"\u7A0B\u5E8F\u5458",capabilities:["coding","debugging"]},{id:"reviewer",name:"\u4EE3\u7801\u5BA1\u67E5\u5458",capabilities:["review","coding"]},{id:"architect",name:"\u67B6\u6784\u5E08",capabilities:["architecture","design"]},{id:"tester",name:"\u6D4B\u8BD5\u5DE5\u7A0B\u5E08",capabilities:["testing","debugging"]},{id:"frontend",name:"\u524D\u7AEF\u5F00\u53D1\u8005",capabilities:["frontend","react"]},{id:"backend",name:"\u540E\u7AEF\u5F00\u53D1\u8005",capabilities:["backend","api-design"]},{id:"devops",name:"DevOps\u5DE5\u7A0B\u5E08",capabilities:["devops","docker"]}],kc=class extends EventEmitter{llmCall;maxSubtasks;maxParallelism;constructor(e){super(),this.llmCall=e.llmCall,this.maxSubtasks=e.maxSubtasks??Om.maxSubtasks,this.maxParallelism=e.maxParallelism??Om.maxParallelism;}setLlmCall(e){this.llmCall=e;}async decompose(e,t){m.info("LLM_DECOMPOSER","Starting task decomposition",{taskId:e.id,description:e.description.slice(0,100)}),this.emit("decomposition_started",{taskId:e.id});let s=this.buildPrompt(e,t),n=await this.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u5206\u89E3\u4E13\u5BB6\uFF0C\u64C5\u957F\u5C06\u590D\u6742\u4EFB\u52A1\u62C6\u5206\u4E3A\u53EF\u6267\u884C\u7684\u5B50\u4EFB\u52A1\u3002",s),r=this.parseResponse(n,e);return this.validateDecomposition(r),this.emit("decomposition_completed",{taskId:e.id,subtaskCount:r.subtasks.length}),r}buildPrompt(e,t){let s=PC.map(r=>`- ${r.id}: ${r.name} (${r.capabilities.join(", ")})`).join(`
3160
+ 5. \u6BCF\u4E2A\u5B50\u4EFB\u52A1\u5BF9\u5E94\u4E00\u4E2A\u89D2\u8272`,DC=[{id:"programmer",name:"\u7A0B\u5E8F\u5458",capabilities:["coding","debugging"]},{id:"reviewer",name:"\u4EE3\u7801\u5BA1\u67E5\u5458",capabilities:["review","coding"]},{id:"architect",name:"\u67B6\u6784\u5E08",capabilities:["architecture","design"]},{id:"tester",name:"\u6D4B\u8BD5\u5DE5\u7A0B\u5E08",capabilities:["testing","debugging"]},{id:"frontend",name:"\u524D\u7AEF\u5F00\u53D1\u8005",capabilities:["frontend","react"]},{id:"backend",name:"\u540E\u7AEF\u5F00\u53D1\u8005",capabilities:["backend","api-design"]},{id:"devops",name:"DevOps\u5DE5\u7A0B\u5E08",capabilities:["devops","docker"]}],kc=class extends EventEmitter{llmCall;maxSubtasks;maxParallelism;constructor(e){super(),this.llmCall=e.llmCall,this.maxSubtasks=e.maxSubtasks??Om.maxSubtasks,this.maxParallelism=e.maxParallelism??Om.maxParallelism;}setLlmCall(e){this.llmCall=e;}async decompose(e,t){m.info("LLM_DECOMPOSER","Starting task decomposition",{taskId:e.id,description:e.description.slice(0,100)}),this.emit("decomposition_started",{taskId:e.id});let s=this.buildPrompt(e,t),n=await this.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u5206\u89E3\u4E13\u5BB6\uFF0C\u64C5\u957F\u5C06\u590D\u6742\u4EFB\u52A1\u62C6\u5206\u4E3A\u53EF\u6267\u884C\u7684\u5B50\u4EFB\u52A1\u3002",s),r=this.parseResponse(n,e);return this.validateDecomposition(r),this.emit("decomposition_completed",{taskId:e.id,subtaskCount:r.subtasks.length}),r}buildPrompt(e,t){let s=DC.map(r=>`- ${r.id}: ${r.name} (${r.capabilities.join(", ")})`).join(`
3161
3161
  `),n=t?.constraints?.length?t.constraints.map(r=>`- ${r}`).join(`
3162
- `):"";return MC.replace("{userRequest}",e.userRequest).replace("{taskDescription}",e.description).replace("{availableRoles}",s).replace("{maxSubtasks}",String(this.maxSubtasks)).replace("{maxParallelism}",String(this.maxParallelism)).replace("{additionalConstraints}",n)}parseResponse(e,t){let s=e.match(/\{[\s\S]*\}/);if(!s)throw new Error("No JSON found in LLM response");let n=JSON.parse(s[0]);if(!n.subtasks||!Array.isArray(n.subtasks))throw new Error("Invalid subtasks in response");let r=n.subtasks.map((l,c)=>({id:l.id||`task-${c+1}`,description:l.description,assignedAgent:void 0,estimatedTime:l.estimatedComplexity*1e4,estimatedTokens:l.estimatedComplexity*1e3,dependencies:l.dependencies||[],priority:1,requiredCapabilities:l.requiredCapabilities,inputs:l.inputs,outputs:l.outputs})),i=this.buildExecutionLevels(r,n.executionStrategy),o=new Map;for(let l of r)o.set(l.id,l.dependencies||[]);return {subtasks:r,executionLevels:i,dependencyGraph:o,criticalPath:n.executionStrategy?.criticalPath||[],estimatedTotalTime:n.executionStrategy?.estimatedTotalTime||6e4,reasoning:n.reasoning||""}}buildExecutionLevels(e,t){return t?.parallelGroups?.length?t.parallelGroups:this.calculateLevelsFromDependencies(e)}calculateLevelsFromDependencies(e){let t=[],s=new Set;new Map(e.map(r=>[r.id,r]));for(;s.size<e.length;){let r=[];for(let i of e){if(s.has(i.id))continue;(i.dependencies||[]).every(c=>s.has(c))&&r.push(i.id);}if(r.length===0){let i=e.filter(o=>!s.has(o.id));t.push(i.map(o=>o.id));break}t.push(r),r.forEach(i=>s.add(i));}return t}validateDecomposition(e){if(e.subtasks.length===0)throw new Error("\u5206\u89E3\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B50\u4EFB\u52A1");for(let s of e.subtasks){if(!s.description||s.description.length<5)throw new Error(`\u5B50\u4EFB\u52A1 ${s.id} \u63CF\u8FF0\u4E0D\u5B8C\u6574`);if(!s.id)throw new Error("\u5B50\u4EFB\u52A1\u7F3A\u5C11 ID")}if(this.hasCyclicDependency(e.dependencyGraph))throw new Error("\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56\uFF0C\u8BF7\u68C0\u67E5\u5B50\u4EFB\u52A1\u4F9D\u8D56\u5173\u7CFB");let t=new Set(e.subtasks.map(s=>s.id));for(let s of e.subtasks)for(let n of s.dependencies||[])if(!t.has(n))throw new Error(`\u5B50\u4EFB\u52A1 ${s.id} \u4F9D\u8D56\u4E86\u4E0D\u5B58\u5728\u7684\u4EFB\u52A1 ${n}`);m.debug("LLM_DECOMPOSER","Decomposition validated",{subtaskCount:e.subtasks.length,levelCount:e.executionLevels.length});}hasCyclicDependency(e){let t=new Set,s=new Set,n=r=>{t.add(r),s.add(r);let i=e.get(r)||[];for(let o of i)if(t.has(o)){if(s.has(o))return true}else if(n(o))return true;return s.delete(r),false};for(let r of e.keys())if(!t.has(r)&&n(r))return true;return false}};function Sc(a){return new kc(a)}var xc=class extends EventEmitter{registry;config;proposalCounter=0;llmDecomposer;constructor(e,t){super(),this.registry=e,this.config={maxSubtasks:t?.maxSubtasks??10,maxParallelism:t?.maxParallelism??5,enableRiskAssessment:t?.enableRiskAssessment??true,optimizeTimeEstimates:t?.optimizeTimeEstimates??true,llmCall:t?.llmCall},t?.llmCall&&(this.llmDecomposer=Sc({llmCall:t.llmCall,maxSubtasks:this.config.maxSubtasks,maxParallelism:this.config.maxParallelism}));}setLlmCall(e){this.config.llmCall=e,this.llmDecomposer?this.llmDecomposer.setLlmCall(e):this.llmDecomposer=Sc({llmCall:e,maxSubtasks:this.config.maxSubtasks,maxParallelism:this.config.maxParallelism});}async generateProposal(e,t,s,n){let r=n?.strategy??"hybrid",i=n?.proposer??"system";this.emit("generation_started",{sessionId:e,taskId:t.id,strategy:r});let o=await this.decomposeTask(t,s,r),l=this.assignTasks(o.subtasks,s);for(let p of o.subtasks){let h=l.assignments.get(p.id);h&&(p.assignedAgent=h);}let c=this.config.enableRiskAssessment?this.assessRisks(o,l,s):[],d={id:this.generateProposalId(e),sessionId:e,proposer:i,version:1,subtasks:o.subtasks,executionLevels:o.executionLevels,estimatedTotalTime:o.estimatedTotalTime,estimatedTotalTokens:this.calculateTotalTokens(o.subtasks),risks:c,createdAt:Date.now()};return this.emit("proposal_generated",{sessionId:e,proposal:d}),d}async decomposeTask(e,t,s){switch(s){case "llm_driven":return this.config.llmCall?this.llmDrivenDecomposition(e,t):this.hybridDecomposition(e,t);case "sequential":return this.sequentialDecomposition(e,t);case "parallel":return this.parallelDecomposition(e,t);case "capability":return this.capabilityBasedDecomposition(e,t);default:return this.hybridDecomposition(e,t)}}sequentialDecomposition(e,t){let s=[],n=[];for(let r=0;r<t.length;r++){let i=t[r],o=`subtask-${r+1}`;s.push({id:o,description:i.proposedApproach,assignedAgent:i.agentId,estimatedTime:i.estimatedTime,estimatedTokens:i.resourceRequirements.estimatedTokens,dependencies:r>0?[`subtask-${r}`]:[],priority:1}),n.push([o]);}return {subtasks:s,executionLevels:n,dependencyGraph:this.buildDependencyGraph(s),criticalPath:s.map(r=>r.id),estimatedTotalTime:s.reduce((r,i)=>r+i.estimatedTime,0)}}parallelDecomposition(e,t){let s=[],n=[],r=Math.min(t.length,this.config.maxParallelism);for(let o=0;o<r;o++){let l=t[o],c=`subtask-${o+1}`;s.push({id:c,description:l.proposedApproach,assignedAgent:l.agentId,estimatedTime:l.estimatedTime,estimatedTokens:l.resourceRequirements.estimatedTokens,dependencies:[],priority:1}),n.push(c);}let i=Math.max(...s.map(o=>o.estimatedTime));return {subtasks:s,executionLevels:[n],dependencyGraph:this.buildDependencyGraph(s),criticalPath:[s[0]?.id].filter(Boolean),estimatedTotalTime:i}}hybridDecomposition(e,t){let s=[],n=[],r=e.estimatedComplexity,i=Math.min(3,Math.ceil(r/3)),o=Math.ceil(t.length/i);for(let u=0;u<i;u++){let d=[],p=u*o,h=Math.min(p+o,t.length);for(let g=p;g<h;g++){let f=t[g],b=`subtask-${u+1}-${g-p+1}`,y=u>0?n[u-1]:[];s.push({id:b,description:f.proposedApproach,assignedAgent:f.agentId,estimatedTime:f.estimatedTime,estimatedTokens:f.resourceRequirements.estimatedTokens,dependencies:y,priority:i-u}),d.push(b);}n.push(d);}let l=this.findCriticalPath(s,n),c=0;for(let u of n){let d=s.filter(p=>u.includes(p.id));c+=Math.max(...d.map(p=>p.estimatedTime));}return {subtasks:s,executionLevels:n,dependencyGraph:this.buildDependencyGraph(s),criticalPath:l,estimatedTotalTime:c}}capabilityBasedDecomposition(e,t){let s=[],n=new Map;for(let o of t){let c=this.registry.get(o.agentId)?.capabilities[0]??"general";n.has(c)||n.set(c,[]),n.get(c).push(o);}let r=[[]],i=0;for(let[o,l]of n)for(let c of l){let u=`subtask-${o}-${++i}`;s.push({id:u,description:`[${o}] ${c.proposedApproach}`,assignedAgent:c.agentId,estimatedTime:c.estimatedTime,estimatedTokens:c.resourceRequirements.estimatedTokens,dependencies:[],priority:1}),r[0].push(u);}return {subtasks:s,executionLevels:r,dependencyGraph:this.buildDependencyGraph(s),criticalPath:s.length>0?[s[0].id]:[],estimatedTotalTime:Math.max(...s.map(o=>o.estimatedTime),0)}}async llmDrivenDecomposition(e,t){if(!this.llmDecomposer)return this.hybridDecomposition(e,t);try{let s=await this.llmDecomposer.decompose(e);return {subtasks:s.subtasks,executionLevels:s.executionLevels,dependencyGraph:s.dependencyGraph,criticalPath:s.criticalPath,estimatedTotalTime:s.estimatedTotalTime}}catch(s){return this.emit("llm_decomposition_failed",{error:s}),this.hybridDecomposition(e,t)}}assignTasks(e,t){let s=new Map,n=new Map,r=[];for(let i of t)n.set(i.agentId,0);for(let i of e)if(i.assignedAgent){s.set(i.id,i.assignedAgent);let o=n.get(i.assignedAgent)??0;n.set(i.assignedAgent,o+i.estimatedTime);}else {let o=null,l=1/0;for(let[c,u]of n)u<l&&(l=u,o=c);o?(s.set(i.id,o),n.set(o,l+i.estimatedTime)):r.push(i.id);}return {assignments:s,loadDistribution:n,unassigned:r}}assessRisks(e,t,s){let n=[];t.unassigned.length>0&&n.push({type:"resource_shortage",description:`${t.unassigned.length} \u4E2A\u4EFB\u52A1\u672A\u80FD\u5206\u914D Agent`,severity:"high",mitigation:"\u589E\u52A0\u53EF\u7528 Agent \u6216\u91CD\u65B0\u5206\u914D\u4EFB\u52A1"});let r=Array.from(t.loadDistribution.values());if(r.length>0){let i=Math.max(...r),o=Math.min(...r),l=i>0?(i-o)/i:0;l>.5&&n.push({type:"load_imbalance",description:`\u8D1F\u8F7D\u4E0D\u5747\u8861 (\u5DEE\u5F02: ${(l*100).toFixed(0)}%)`,severity:"medium",mitigation:"\u91CD\u65B0\u5206\u914D\u4EFB\u52A1\u4EE5\u5E73\u8861\u8D1F\u8F7D"});}for(let i of s)i.confidence<.5&&n.push({type:"low_confidence",description:`Agent ${i.agentId} \u7F6E\u4FE1\u5EA6\u8F83\u4F4E (${(i.confidence*100).toFixed(0)}%)`,severity:"medium",mitigation:"\u8003\u8651\u5206\u914D\u7ED9\u5176\u4ED6 Agent \u6216\u964D\u4F4E\u4EFB\u52A1\u590D\u6742\u5EA6"});return e.criticalPath.length>5&&n.push({type:"long_critical_path",description:`\u5173\u952E\u8DEF\u5F84\u8F83\u957F (${e.criticalPath.length} \u6B65)`,severity:"low",mitigation:"\u8003\u8651\u589E\u52A0\u5E76\u884C\u5EA6"}),n}async optimizeProposal(e,t){if(!this.config.llmCall)return e;let s=`
3162
+ `):"";return PC.replace("{userRequest}",e.userRequest).replace("{taskDescription}",e.description).replace("{availableRoles}",s).replace("{maxSubtasks}",String(this.maxSubtasks)).replace("{maxParallelism}",String(this.maxParallelism)).replace("{additionalConstraints}",n)}parseResponse(e,t){let s=e.match(/\{[\s\S]*\}/);if(!s)throw new Error("No JSON found in LLM response");let n=JSON.parse(s[0]);if(!n.subtasks||!Array.isArray(n.subtasks))throw new Error("Invalid subtasks in response");let r=n.subtasks.map((l,c)=>({id:l.id||`task-${c+1}`,description:l.description,assignedAgent:void 0,estimatedTime:l.estimatedComplexity*1e4,estimatedTokens:l.estimatedComplexity*1e3,dependencies:l.dependencies||[],priority:1,requiredCapabilities:l.requiredCapabilities,inputs:l.inputs,outputs:l.outputs})),i=this.buildExecutionLevels(r,n.executionStrategy),o=new Map;for(let l of r)o.set(l.id,l.dependencies||[]);return {subtasks:r,executionLevels:i,dependencyGraph:o,criticalPath:n.executionStrategy?.criticalPath||[],estimatedTotalTime:n.executionStrategy?.estimatedTotalTime||6e4,reasoning:n.reasoning||""}}buildExecutionLevels(e,t){return t?.parallelGroups?.length?t.parallelGroups:this.calculateLevelsFromDependencies(e)}calculateLevelsFromDependencies(e){let t=[],s=new Set;new Map(e.map(r=>[r.id,r]));for(;s.size<e.length;){let r=[];for(let i of e){if(s.has(i.id))continue;(i.dependencies||[]).every(c=>s.has(c))&&r.push(i.id);}if(r.length===0){let i=e.filter(o=>!s.has(o.id));t.push(i.map(o=>o.id));break}t.push(r),r.forEach(i=>s.add(i));}return t}validateDecomposition(e){if(e.subtasks.length===0)throw new Error("\u5206\u89E3\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B50\u4EFB\u52A1");for(let s of e.subtasks){if(!s.description||s.description.length<5)throw new Error(`\u5B50\u4EFB\u52A1 ${s.id} \u63CF\u8FF0\u4E0D\u5B8C\u6574`);if(!s.id)throw new Error("\u5B50\u4EFB\u52A1\u7F3A\u5C11 ID")}if(this.hasCyclicDependency(e.dependencyGraph))throw new Error("\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56\uFF0C\u8BF7\u68C0\u67E5\u5B50\u4EFB\u52A1\u4F9D\u8D56\u5173\u7CFB");let t=new Set(e.subtasks.map(s=>s.id));for(let s of e.subtasks)for(let n of s.dependencies||[])if(!t.has(n))throw new Error(`\u5B50\u4EFB\u52A1 ${s.id} \u4F9D\u8D56\u4E86\u4E0D\u5B58\u5728\u7684\u4EFB\u52A1 ${n}`);m.debug("LLM_DECOMPOSER","Decomposition validated",{subtaskCount:e.subtasks.length,levelCount:e.executionLevels.length});}hasCyclicDependency(e){let t=new Set,s=new Set,n=r=>{t.add(r),s.add(r);let i=e.get(r)||[];for(let o of i)if(t.has(o)){if(s.has(o))return true}else if(n(o))return true;return s.delete(r),false};for(let r of e.keys())if(!t.has(r)&&n(r))return true;return false}};function Sc(a){return new kc(a)}var xc=class extends EventEmitter{registry;config;proposalCounter=0;llmDecomposer;constructor(e,t){super(),this.registry=e,this.config={maxSubtasks:t?.maxSubtasks??10,maxParallelism:t?.maxParallelism??5,enableRiskAssessment:t?.enableRiskAssessment??true,optimizeTimeEstimates:t?.optimizeTimeEstimates??true,llmCall:t?.llmCall},t?.llmCall&&(this.llmDecomposer=Sc({llmCall:t.llmCall,maxSubtasks:this.config.maxSubtasks,maxParallelism:this.config.maxParallelism}));}setLlmCall(e){this.config.llmCall=e,this.llmDecomposer?this.llmDecomposer.setLlmCall(e):this.llmDecomposer=Sc({llmCall:e,maxSubtasks:this.config.maxSubtasks,maxParallelism:this.config.maxParallelism});}async generateProposal(e,t,s,n){let r=n?.strategy??"hybrid",i=n?.proposer??"system";this.emit("generation_started",{sessionId:e,taskId:t.id,strategy:r});let o=await this.decomposeTask(t,s,r),l=this.assignTasks(o.subtasks,s);for(let p of o.subtasks){let h=l.assignments.get(p.id);h&&(p.assignedAgent=h);}let c=this.config.enableRiskAssessment?this.assessRisks(o,l,s):[],d={id:this.generateProposalId(e),sessionId:e,proposer:i,version:1,subtasks:o.subtasks,executionLevels:o.executionLevels,estimatedTotalTime:o.estimatedTotalTime,estimatedTotalTokens:this.calculateTotalTokens(o.subtasks),risks:c,createdAt:Date.now()};return this.emit("proposal_generated",{sessionId:e,proposal:d}),d}async decomposeTask(e,t,s){switch(s){case "llm_driven":return this.config.llmCall?this.llmDrivenDecomposition(e,t):this.hybridDecomposition(e,t);case "sequential":return this.sequentialDecomposition(e,t);case "parallel":return this.parallelDecomposition(e,t);case "capability":return this.capabilityBasedDecomposition(e,t);default:return this.hybridDecomposition(e,t)}}sequentialDecomposition(e,t){let s=[],n=[];for(let r=0;r<t.length;r++){let i=t[r],o=`subtask-${r+1}`;s.push({id:o,description:i.proposedApproach,assignedAgent:i.agentId,estimatedTime:i.estimatedTime,estimatedTokens:i.resourceRequirements.estimatedTokens,dependencies:r>0?[`subtask-${r}`]:[],priority:1}),n.push([o]);}return {subtasks:s,executionLevels:n,dependencyGraph:this.buildDependencyGraph(s),criticalPath:s.map(r=>r.id),estimatedTotalTime:s.reduce((r,i)=>r+i.estimatedTime,0)}}parallelDecomposition(e,t){let s=[],n=[],r=Math.min(t.length,this.config.maxParallelism);for(let o=0;o<r;o++){let l=t[o],c=`subtask-${o+1}`;s.push({id:c,description:l.proposedApproach,assignedAgent:l.agentId,estimatedTime:l.estimatedTime,estimatedTokens:l.resourceRequirements.estimatedTokens,dependencies:[],priority:1}),n.push(c);}let i=Math.max(...s.map(o=>o.estimatedTime));return {subtasks:s,executionLevels:[n],dependencyGraph:this.buildDependencyGraph(s),criticalPath:[s[0]?.id].filter(Boolean),estimatedTotalTime:i}}hybridDecomposition(e,t){let s=[],n=[],r=e.estimatedComplexity,i=Math.min(3,Math.ceil(r/3)),o=Math.ceil(t.length/i);for(let u=0;u<i;u++){let d=[],p=u*o,h=Math.min(p+o,t.length);for(let g=p;g<h;g++){let f=t[g],b=`subtask-${u+1}-${g-p+1}`,y=u>0?n[u-1]:[];s.push({id:b,description:f.proposedApproach,assignedAgent:f.agentId,estimatedTime:f.estimatedTime,estimatedTokens:f.resourceRequirements.estimatedTokens,dependencies:y,priority:i-u}),d.push(b);}n.push(d);}let l=this.findCriticalPath(s,n),c=0;for(let u of n){let d=s.filter(p=>u.includes(p.id));c+=Math.max(...d.map(p=>p.estimatedTime));}return {subtasks:s,executionLevels:n,dependencyGraph:this.buildDependencyGraph(s),criticalPath:l,estimatedTotalTime:c}}capabilityBasedDecomposition(e,t){let s=[],n=new Map;for(let o of t){let c=this.registry.get(o.agentId)?.capabilities[0]??"general";n.has(c)||n.set(c,[]),n.get(c).push(o);}let r=[[]],i=0;for(let[o,l]of n)for(let c of l){let u=`subtask-${o}-${++i}`;s.push({id:u,description:`[${o}] ${c.proposedApproach}`,assignedAgent:c.agentId,estimatedTime:c.estimatedTime,estimatedTokens:c.resourceRequirements.estimatedTokens,dependencies:[],priority:1}),r[0].push(u);}return {subtasks:s,executionLevels:r,dependencyGraph:this.buildDependencyGraph(s),criticalPath:s.length>0?[s[0].id]:[],estimatedTotalTime:Math.max(...s.map(o=>o.estimatedTime),0)}}async llmDrivenDecomposition(e,t){if(!this.llmDecomposer)return this.hybridDecomposition(e,t);try{let s=await this.llmDecomposer.decompose(e);return {subtasks:s.subtasks,executionLevels:s.executionLevels,dependencyGraph:s.dependencyGraph,criticalPath:s.criticalPath,estimatedTotalTime:s.estimatedTotalTime}}catch(s){return this.emit("llm_decomposition_failed",{error:s}),this.hybridDecomposition(e,t)}}assignTasks(e,t){let s=new Map,n=new Map,r=[];for(let i of t)n.set(i.agentId,0);for(let i of e)if(i.assignedAgent){s.set(i.id,i.assignedAgent);let o=n.get(i.assignedAgent)??0;n.set(i.assignedAgent,o+i.estimatedTime);}else {let o=null,l=1/0;for(let[c,u]of n)u<l&&(l=u,o=c);o?(s.set(i.id,o),n.set(o,l+i.estimatedTime)):r.push(i.id);}return {assignments:s,loadDistribution:n,unassigned:r}}assessRisks(e,t,s){let n=[];t.unassigned.length>0&&n.push({type:"resource_shortage",description:`${t.unassigned.length} \u4E2A\u4EFB\u52A1\u672A\u80FD\u5206\u914D Agent`,severity:"high",mitigation:"\u589E\u52A0\u53EF\u7528 Agent \u6216\u91CD\u65B0\u5206\u914D\u4EFB\u52A1"});let r=Array.from(t.loadDistribution.values());if(r.length>0){let i=Math.max(...r),o=Math.min(...r),l=i>0?(i-o)/i:0;l>.5&&n.push({type:"load_imbalance",description:`\u8D1F\u8F7D\u4E0D\u5747\u8861 (\u5DEE\u5F02: ${(l*100).toFixed(0)}%)`,severity:"medium",mitigation:"\u91CD\u65B0\u5206\u914D\u4EFB\u52A1\u4EE5\u5E73\u8861\u8D1F\u8F7D"});}for(let i of s)i.confidence<.5&&n.push({type:"low_confidence",description:`Agent ${i.agentId} \u7F6E\u4FE1\u5EA6\u8F83\u4F4E (${(i.confidence*100).toFixed(0)}%)`,severity:"medium",mitigation:"\u8003\u8651\u5206\u914D\u7ED9\u5176\u4ED6 Agent \u6216\u964D\u4F4E\u4EFB\u52A1\u590D\u6742\u5EA6"});return e.criticalPath.length>5&&n.push({type:"long_critical_path",description:`\u5173\u952E\u8DEF\u5F84\u8F83\u957F (${e.criticalPath.length} \u6B65)`,severity:"low",mitigation:"\u8003\u8651\u589E\u52A0\u5E76\u884C\u5EA6"}),n}async optimizeProposal(e,t){if(!this.config.llmCall)return e;let s=`
3163
3163
  \u5F53\u524D\u63D0\u6848\uFF1A
3164
3164
  ${JSON.stringify(e,null,2)}
3165
3165
 
@@ -3192,14 +3192,14 @@ ${n.length>0?n.join(`
3192
3192
  "adoptedSuggestions": ["\u91C7\u7EB3\u7684\u5EFA\u8BAE1", "\u91C7\u7EB3\u7684\u5EFA\u8BAE2"],
3193
3193
  "deferredDisagreements": ["\u6401\u7F6E\u7684\u5206\u6B671"],
3194
3194
  "executionNotes": ["\u6267\u884C\u6CE8\u610F\u4E8B\u98791", "\u6267\u884C\u6CE8\u610F\u4E8B\u98792"]
3195
- }`}parseSummaryResponse(e){try{let t=e.match(/\{[\s\S]*\}/);if(t){let s=JSON.parse(t[0]);return {finalDecision:s.finalDecision||"\u534F\u5546\u5B8C\u6210",adoptedSuggestions:s.adoptedSuggestions||[],deferredDisagreements:s.deferredDisagreements||[],executionNotes:s.executionNotes||[]}}}catch{m.warn("NEGOTIATION_SUMMARIZER","Failed to parse response");}return {finalDecision:e.slice(0,500),adoptedSuggestions:[],deferredDisagreements:[],executionNotes:[]}}};function $m(a){return new Tc(a)}var NC={defaultMaxRetries:2,defaultMutable:true,autoCalculateLevels:true,validateDAG:true},_c=class extends EventEmitter{config;dags=new Map;dagCounter=0;constructor(e){super(),this.config={...NC,...e};}createFromProposal(e,t){let s=this.generateDAGId(e.id),n=new Map;for(let c of e.subtasks){let u=this.createNode(c,{mutable:t?.mutable??this.config.defaultMutable,maxRetries:t?.maxRetries??this.config.defaultMaxRetries});n.set(u.id,u);}let r=this.config.autoCalculateLevels?this.calculateLevels(n):e.executionLevels;for(let c=0;c<r.length;c++)for(let u of r[c]){let d=n.get(u);d&&(d.level=c);}let i=this.calculateCriticalPath(n,r),o=this.calculateEstimatedTime(n,r),l={id:s,proposalId:e.id,nodes:n,version:1,history:[],status:"planning",analysis:{levels:r,maxParallelism:Math.max(...r.map(c=>c.length)),criticalPath:i,estimatedTotalTime:o},context:new Map(Object.entries(t?.initialContext??{})),createdAt:Date.now()};if(this.config.validateDAG){let c=this.validate(l);c.valid||this.emit("validation_failed",{dagId:s,errors:c.errors});}return this.dags.set(s,l),this.emit("dag_created",{dagId:s,proposalId:e.id,nodeCount:n.size,levels:r.length}),l}createNode(e,t){return {id:e.id,task:{description:e.description,inputMapping:e.inputMapping??{},outputKey:e.outputKey??`output_${e.id}`,estimatedTime:e.estimatedTime,estimatedTokens:e.estimatedTokens,requiredCapabilities:e.requiredCapabilities},assignedAgent:e.assignedAgent??"",dependencies:e.dependencies,status:"pending",level:0,retryCount:0,maxRetries:t.maxRetries,mutable:t.mutable,version:1}}calculateLevels(e){let t=[],s=new Map,n=new Set;for(let[r,i]of e)s.set(r,i.dependencies.length);for(;n.size<e.size;){let r=[];for(let[i,o]of s)o===0&&!n.has(i)&&r.push(i);if(r.length===0)break;for(let i of r){n.add(i);for(let[o,l]of e)l.dependencies.includes(i)&&s.set(o,(s.get(o)??1)-1);}t.push(r);}return t}calculateCriticalPath(e,t){let s=[];for(let n of t){let r=0,i="";for(let o of n){let l=e.get(o);l&&l.task.estimatedTime>r&&(r=l.task.estimatedTime,i=o);}i&&s.push(i);}return s}calculateEstimatedTime(e,t){let s=0;for(let n of t){let r=0;for(let i of n){let o=e.get(i);o&&(r=Math.max(r,o.task.estimatedTime));}s+=r;}return s}validate(e){let t=[],s=[],n=[],r=[];for(let[o,l]of e.nodes){l.assignedAgent||s.push(`Node ${o} has no assigned agent`);let c=l.dependencies.filter(d=>!e.nodes.has(d));c.length>0&&(t.push(`Node ${o} has missing dependencies: ${c.join(", ")}`),r.push({nodeId:o,missingDeps:c}));let u=false;for(let[d,p]of e.nodes)if(d!==o&&p.dependencies.includes(o)){u=true;break}l.dependencies.length===0&&!u&&e.nodes.size>1&&e.nodes.size>1&&e.analysis.levels[0]?.length!==e.nodes.size&&n.push(o);}let i=this.detectCycle(e);return i&&t.push("DAG contains a cycle"),{valid:t.length===0,errors:t,warnings:s,hasCycle:i,orphanNodes:n,missingDependencies:r}}detectCycle(e){let t=new Set,s=new Set,n=r=>{if(t.add(r),s.add(r),!e.nodes.get(r))return false;for(let[o,l]of e.nodes)if(l.dependencies.includes(r)){if(t.has(o)){if(s.has(o))return true}else if(n(o))return true}return s.delete(r),false};for(let r of e.nodes.keys())if(!t.has(r)&&n(r))return true;return false}addNode(e,t,s="system"){let n=this.dags.get(e);if(!n)return null;let r={...t,status:"pending",retryCount:0,version:1};return n.nodes.set(t.id,r),n.version++,this.recordHistory(n,"add",t.id,"Node added",s,void 0,r),this.config.autoCalculateLevels&&this.recalculateAnalysis(n),this.emit("node_added",{dagId:e,nodeId:t.id,version:n.version}),r}removeNode(e,t,s="system"){let n=this.dags.get(e);if(!n)return false;let r=n.nodes.get(t);if(!r)return false;if(!r.mutable)return this.emit("modification_rejected",{dagId:e,nodeId:t,reason:"Node is immutable"}),false;for(let[i,o]of n.nodes)o.dependencies.includes(t)&&(o.dependencies=o.dependencies.filter(l=>l!==t),o.version++);return n.nodes.delete(t),n.version++,this.recordHistory(n,"remove",t,"Node removed",s,r,void 0),this.config.autoCalculateLevels&&this.recalculateAnalysis(n),this.emit("node_removed",{dagId:e,nodeId:t,version:n.version}),true}modifyNode(e,t,s,n="system"){let r=this.dags.get(e);if(!r)return false;let i=r.nodes.get(t);if(!i)return false;if(!i.mutable)return this.emit("modification_rejected",{dagId:e,nodeId:t,reason:"Node is immutable"}),false;let o={...i};return s.task&&(i.task={...i.task,...s.task}),s.dependencies&&(i.dependencies=s.dependencies),s.assignedAgent!==void 0&&(i.assignedAgent=s.assignedAgent),i.version++,r.version++,this.recordHistory(r,"modify",t,"Node modified",n,o,i),s.dependencies&&this.config.autoCalculateLevels&&this.recalculateAnalysis(r),this.emit("node_modified",{dagId:e,nodeId:t,updates:s,version:r.version}),true}reassignAgent(e,t,s,n="system"){let r=this.dags.get(e);if(!r)return false;let i=r.nodes.get(t);if(!i)return false;let o=i.assignedAgent;return i.assignedAgent=s,i.version++,r.version++,this.recordHistory(r,"reassign",t,`Agent reassigned from ${o} to ${s}`,n,o,s),this.emit("agent_reassigned",{dagId:e,nodeId:t,previousAgent:o,newAgent:s,version:r.version}),true}reorderDependencies(e,t,s,n="system"){return this.modifyNode(e,t,{dependencies:s},n)}recordHistory(e,t,s,n,r,i,o){let l={version:e.version,action:t,nodeId:s,reason:n,previousValue:i,newValue:o,operator:r,timestamp:Date.now()};e.history.push(l);}recalculateAnalysis(e){let t=this.calculateLevels(e.nodes);for(let s=0;s<t.length;s++)for(let n of t[s]){let r=e.nodes.get(n);r&&(r.level=s);}e.analysis={levels:t,maxParallelism:Math.max(...t.map(s=>s.length),0),criticalPath:this.calculateCriticalPath(e.nodes,t),estimatedTotalTime:this.calculateEstimatedTime(e.nodes,t)};}getDAG(e){return this.dags.get(e)}getReadyNodes(e){let t=this.dags.get(e);if(!t)return [];let s=[];for(let n of t.nodes.values()){if(n.status!=="pending")continue;n.dependencies.every(i=>t.nodes.get(i)?.status==="completed")&&s.push(n);}return s}updateNodeStatus(e,t,s,n,r){let i=this.dags.get(e);if(!i)return false;let o=i.nodes.get(t);return o?(o.status=s,s==="running"?o.startedAt=Date.now():(s==="completed"||s==="failed")&&(o.completedAt=Date.now()),n&&(o.result=n),r&&(o.error=r),this.emit("node_status_changed",{dagId:e,nodeId:t,status:s,result:n,error:r}),true):false}cloneDAG(e,t){let s=this.dags.get(e);if(!s)return null;let n=t??`${e}-clone-${Date.now()}`,r=new Map;for(let[o,l]of s.nodes)r.set(o,{...l});let i={...s,id:n,nodes:r,history:[...s.history],context:new Map(s.context),createdAt:Date.now()};return this.dags.set(n,i),this.emit("dag_cloned",{originalId:e,clonedId:n}),i}deleteDAG(e){let t=this.dags.delete(e);return t&&this.emit("dag_deleted",{dagId:e}),t}generateDAGId(e){return `dag-${e}-${++this.dagCounter}`}getStats(){let e=0,t=0;for(let s of this.dags.values())s.status==="executing"||s.status==="replanning"?e++:s.status==="completed"&&t++;return {totalDAGs:this.dags.size,activeDAGs:e,completedDAGs:t}}};function Fm(a){return new _c(a)}W();var FC={maxConcurrency:5,nodeTimeout:12e4,allowPartialFailure:true,retryCount:2,retryDelay:1e3,enablePeerReview:true,enableReplanning:true,maxReplanAttempts:3,progressUpdateInterval:1e3,collectDetailedMetrics:true,enableProgressiveExpansion:true},Rc=class extends EventEmitter{registry;dagBuilder;config;agentMatcher;progressiveManager;rgpsDataFlowManager;executionStates=new Map;progressTimers=new Map;currentAbortSignal;constructor(e,t,s){super(),this.registry=e,this.dagBuilder=t,this.agentMatcher=s?.agentMatcher,this.progressiveManager=s?.progressiveManager,this.rgpsDataFlowManager=s?.rgpsDataFlowManager,this.config={...FC,...s};}async execute(e,t){let s=this.dagBuilder.getDAG(e);if(!s)throw new Error(`DAG not found: ${e}`);this.currentAbortSignal=t;let n=this.initializeState(s);s.status="executing",s.startedAt=Date.now(),this.emit("execution_started",{dagId:e,nodeCount:s.nodes.size,levels:s.analysis.levels.length}),this.startProgressUpdates(e,s),this.rgpsDataFlowManager&&this.rgpsDataFlowManager.inferFromDAG(s);try{for(let i=0;i<s.analysis.levels.length&&!n.cancelled;i++){let o=s.analysis.levels[i];this.emit("level_started",{dagId:e,level:i,nodeIds:o}),await this.executeLevel(s,n,i,o),this.config.enableReplanning&&n.failedNodes.size>0&&await this.checkReplanCondition(s,n)&&n.replanCount<this.config.maxReplanAttempts&&await this.triggerReplan(s,n),this.emit("level_completed",{dagId:e,level:i,completedNodes:Array.from(n.completedNodes),failedNodes:Array.from(n.failedNodes)});}}finally{this.stopProgressUpdates(e);}let r=this.buildResult(s,n);return n.cancelled?s.status=n.cancelReason==="paused"?"paused":"cancelled":s.status=r.success?"completed":"failed",s.completedAt=Date.now(),this.executionStates.delete(e),this.emit("execution_completed",{dagId:e,result:r}),r}initializeState(e){let t={dagId:e.id,running:true,startedAt:Date.now(),runningNodes:new Set,completedNodes:new Set,failedNodes:new Set,skippedNodes:new Set,nodeResults:new Map,errors:[],replanCount:0,cancelled:false};for(let[s,n]of e.nodes){if(n.status==="completed"){t.completedNodes.add(s),n.result&&t.nodeResults.set(s,n.result);continue}if(n.status==="failed"){t.failedNodes.add(s),t.errors.push({nodeId:s,error:n.error||"Node failed previously",timestamp:Date.now()});continue}if(n.status==="skipped"){t.skippedNodes.add(s);continue}n.status==="running"&&this.dagBuilder.updateNodeStatus(e.id,s,"pending");}return this.executionStates.set(e.id,t),t}async executeLevel(e,t,s,n){let r=n.filter(o=>{let l=e.nodes.get(o);if(!l||l.status!=="pending")return false;let c=l.dependencies.every(d=>t.completedNodes.has(d));return l.dependencies.some(d=>t.failedNodes.has(d))&&!this.config.allowPartialFailure?(t.skippedNodes.add(o),this.dagBuilder.updateNodeStatus(e.id,o,"skipped"),false):c}),i=this.chunkArray(r,this.config.maxConcurrency);for(let o of i){if(t.cancelled)break;await Promise.all(o.map(l=>this.executeNode(e,t,l)));}}async executeNode(e,t,s){let n=e.nodes.get(s);if(n){t.runningNodes.add(s),this.dagBuilder.updateNodeStatus(e.id,s,"running"),this.emit("node_started",{dagId:e.id,nodeId:s,agentId:n.assignedAgent});try{let r=this.prepareContext(e,n),i=await this.runNode(n,r);if(t.runningNodes.delete(s),t.completedNodes.add(s),t.nodeResults.set(s,i),e.context.set(n.task.outputKey,i.output),i.data)for(let[o,l]of Object.entries(i.data))e.context.set(`${n.task.outputKey}.${o}`,l);this.rgpsDataFlowManager&&this.rgpsDataFlowManager.storeNodeOutput(s,n.task.outputKey,i.output),this.dagBuilder.updateNodeStatus(e.id,s,"completed",i),this.emit("node_completed",{dagId:e.id,nodeId:s,result:i}),this.config.enableProgressiveExpansion&&this.progressiveManager&&await this.checkProgressiveExpansion(e,n,i);}catch(r){let i=r instanceof Error?r.message:String(r);if(n.retryCount<n.maxRetries)return n.retryCount++,this.emit("node_retry",{dagId:e.id,nodeId:s,attempt:n.retryCount,error:i}),await new Promise(o=>setTimeout(o,this.config.retryDelay)),this.executeNode(e,t,s);t.runningNodes.delete(s),t.failedNodes.add(s),t.errors.push({nodeId:s,error:i,timestamp:Date.now()}),this.dagBuilder.updateNodeStatus(e.id,s,"failed",void 0,i),this.emit("node_failed",{dagId:e.id,nodeId:s,error:i,retries:n.retryCount});}}}prepareContext(e,t){let s={};for(let[n,r]of Object.entries(t.task.inputMapping))s[n]=e.context.get(r);for(let n of t.dependencies){let r=e.nodes.get(n);r&&(s[`dep_${n}`]=e.context.get(r.task.outputKey));}return {inputs:s,dagContext:e.context,timeout:this.config.nodeTimeout,abortSignal:this.currentAbortSignal}}async runNode(e,t){let s=Date.now(),n=this.registry.getInstance(e.assignedAgent);if(!n&&this.agentMatcher){m.info("DAG_EXECUTOR","Agent not found, using matcher",{nodeId:e.id,assignedAgent:e.assignedAgent});let d=await this.agentMatcher.matchOrCreate({subtask:{id:e.id,description:e.task.description,dependencies:e.dependencies,estimatedTime:e.task.estimatedTime??6e4,estimatedTokens:e.task.estimatedTokens??5e3,requiredCapabilities:e.task.requiredCapabilities},requiredCapabilities:e.task.requiredCapabilities});n=d.agent,e.assignedAgent=n.id,this.emit("agent_matched",{nodeId:e.id,agentId:n.id,isNewlyCreated:d.isNewlyCreated,score:d.score});}if(!n)throw new Error(`Agent not found: ${e.assignedAgent}`);let r=this.buildTaskDescription(e,t),i=d=>{d.agentId===n.id&&this.emit("node_text",{nodeId:e.id,agentId:d.agentId,text:d.text});},o=d=>{d.agentId===n.id&&this.emit("node_tool_start",{nodeId:e.id,agentId:d.agentId,tool:d.tool,toolId:d.toolId,args:d.args,targetPath:d.targetPath,description:d.description});},l=d=>{d.agentId===n.id&&this.emit("node_tool_end",{nodeId:e.id,agentId:d.agentId,tool:d.tool,toolId:d.toolId,success:d.success,output:d.output,outputTruncated:d.outputTruncated,args:d.args,summary:d.summary,duration:d.duration});};n.on("task_text",i),n.on("task_tool_start",o),n.on("task_tool_end",l);let c=await Promise.race([n.executeTask(r,void 0,void 0,{abortSignal:t.abortSignal}),this.createTimeout(t.timeout,e.id)]).finally(()=>{n.off("task_text",i),n.off("task_tool_start",o),n.off("task_tool_end",l);}),u=Date.now()-s;return {output:c.output,data:c.data,tokenUsage:c.tokenUsage??{input:0,output:0,total:0},duration:u,toolCalls:c.toolCalls}}buildTaskDescription(e,t){if(this.rgpsDataFlowManager)return this.rgpsDataFlowManager.buildTaskDescription(e.id,e.task.description);let s=e.task.description;if(Object.keys(t.inputs).length>0){s+=`
3195
+ }`}parseSummaryResponse(e){try{let t=e.match(/\{[\s\S]*\}/);if(t){let s=JSON.parse(t[0]);return {finalDecision:s.finalDecision||"\u534F\u5546\u5B8C\u6210",adoptedSuggestions:s.adoptedSuggestions||[],deferredDisagreements:s.deferredDisagreements||[],executionNotes:s.executionNotes||[]}}}catch{m.warn("NEGOTIATION_SUMMARIZER","Failed to parse response");}return {finalDecision:e.slice(0,500),adoptedSuggestions:[],deferredDisagreements:[],executionNotes:[]}}};function $m(a){return new Tc(a)}var $C={defaultMaxRetries:2,defaultMutable:true,autoCalculateLevels:true,validateDAG:true},_c=class extends EventEmitter{config;dags=new Map;dagCounter=0;constructor(e){super(),this.config={...$C,...e};}createFromProposal(e,t){let s=this.generateDAGId(e.id),n=new Map;for(let c of e.subtasks){let u=this.createNode(c,{mutable:t?.mutable??this.config.defaultMutable,maxRetries:t?.maxRetries??this.config.defaultMaxRetries});n.set(u.id,u);}let r=this.config.autoCalculateLevels?this.calculateLevels(n):e.executionLevels;for(let c=0;c<r.length;c++)for(let u of r[c]){let d=n.get(u);d&&(d.level=c);}let i=this.calculateCriticalPath(n,r),o=this.calculateEstimatedTime(n,r),l={id:s,proposalId:e.id,nodes:n,version:1,history:[],status:"planning",analysis:{levels:r,maxParallelism:Math.max(...r.map(c=>c.length)),criticalPath:i,estimatedTotalTime:o},context:new Map(Object.entries(t?.initialContext??{})),createdAt:Date.now()};if(this.config.validateDAG){let c=this.validate(l);c.valid||this.emit("validation_failed",{dagId:s,errors:c.errors});}return this.dags.set(s,l),this.emit("dag_created",{dagId:s,proposalId:e.id,nodeCount:n.size,levels:r.length}),l}createNode(e,t){return {id:e.id,task:{description:e.description,inputMapping:e.inputMapping??{},outputKey:e.outputKey??`output_${e.id}`,estimatedTime:e.estimatedTime,estimatedTokens:e.estimatedTokens,requiredCapabilities:e.requiredCapabilities},assignedAgent:e.assignedAgent??"",dependencies:e.dependencies,status:"pending",level:0,retryCount:0,maxRetries:t.maxRetries,mutable:t.mutable,version:1}}calculateLevels(e){let t=[],s=new Map,n=new Set;for(let[r,i]of e)s.set(r,i.dependencies.length);for(;n.size<e.size;){let r=[];for(let[i,o]of s)o===0&&!n.has(i)&&r.push(i);if(r.length===0)break;for(let i of r){n.add(i);for(let[o,l]of e)l.dependencies.includes(i)&&s.set(o,(s.get(o)??1)-1);}t.push(r);}return t}calculateCriticalPath(e,t){let s=[];for(let n of t){let r=0,i="";for(let o of n){let l=e.get(o);l&&l.task.estimatedTime>r&&(r=l.task.estimatedTime,i=o);}i&&s.push(i);}return s}calculateEstimatedTime(e,t){let s=0;for(let n of t){let r=0;for(let i of n){let o=e.get(i);o&&(r=Math.max(r,o.task.estimatedTime));}s+=r;}return s}validate(e){let t=[],s=[],n=[],r=[];for(let[o,l]of e.nodes){l.assignedAgent||s.push(`Node ${o} has no assigned agent`);let c=l.dependencies.filter(d=>!e.nodes.has(d));c.length>0&&(t.push(`Node ${o} has missing dependencies: ${c.join(", ")}`),r.push({nodeId:o,missingDeps:c}));let u=false;for(let[d,p]of e.nodes)if(d!==o&&p.dependencies.includes(o)){u=true;break}l.dependencies.length===0&&!u&&e.nodes.size>1&&e.nodes.size>1&&e.analysis.levels[0]?.length!==e.nodes.size&&n.push(o);}let i=this.detectCycle(e);return i&&t.push("DAG contains a cycle"),{valid:t.length===0,errors:t,warnings:s,hasCycle:i,orphanNodes:n,missingDependencies:r}}detectCycle(e){let t=new Set,s=new Set,n=r=>{if(t.add(r),s.add(r),!e.nodes.get(r))return false;for(let[o,l]of e.nodes)if(l.dependencies.includes(r)){if(t.has(o)){if(s.has(o))return true}else if(n(o))return true}return s.delete(r),false};for(let r of e.nodes.keys())if(!t.has(r)&&n(r))return true;return false}addNode(e,t,s="system"){let n=this.dags.get(e);if(!n)return null;let r={...t,status:"pending",retryCount:0,version:1};return n.nodes.set(t.id,r),n.version++,this.recordHistory(n,"add",t.id,"Node added",s,void 0,r),this.config.autoCalculateLevels&&this.recalculateAnalysis(n),this.emit("node_added",{dagId:e,nodeId:t.id,version:n.version}),r}removeNode(e,t,s="system"){let n=this.dags.get(e);if(!n)return false;let r=n.nodes.get(t);if(!r)return false;if(!r.mutable)return this.emit("modification_rejected",{dagId:e,nodeId:t,reason:"Node is immutable"}),false;for(let[i,o]of n.nodes)o.dependencies.includes(t)&&(o.dependencies=o.dependencies.filter(l=>l!==t),o.version++);return n.nodes.delete(t),n.version++,this.recordHistory(n,"remove",t,"Node removed",s,r,void 0),this.config.autoCalculateLevels&&this.recalculateAnalysis(n),this.emit("node_removed",{dagId:e,nodeId:t,version:n.version}),true}modifyNode(e,t,s,n="system"){let r=this.dags.get(e);if(!r)return false;let i=r.nodes.get(t);if(!i)return false;if(!i.mutable)return this.emit("modification_rejected",{dagId:e,nodeId:t,reason:"Node is immutable"}),false;let o={...i};return s.task&&(i.task={...i.task,...s.task}),s.dependencies&&(i.dependencies=s.dependencies),s.assignedAgent!==void 0&&(i.assignedAgent=s.assignedAgent),i.version++,r.version++,this.recordHistory(r,"modify",t,"Node modified",n,o,i),s.dependencies&&this.config.autoCalculateLevels&&this.recalculateAnalysis(r),this.emit("node_modified",{dagId:e,nodeId:t,updates:s,version:r.version}),true}reassignAgent(e,t,s,n="system"){let r=this.dags.get(e);if(!r)return false;let i=r.nodes.get(t);if(!i)return false;let o=i.assignedAgent;return i.assignedAgent=s,i.version++,r.version++,this.recordHistory(r,"reassign",t,`Agent reassigned from ${o} to ${s}`,n,o,s),this.emit("agent_reassigned",{dagId:e,nodeId:t,previousAgent:o,newAgent:s,version:r.version}),true}reorderDependencies(e,t,s,n="system"){return this.modifyNode(e,t,{dependencies:s},n)}recordHistory(e,t,s,n,r,i,o){let l={version:e.version,action:t,nodeId:s,reason:n,previousValue:i,newValue:o,operator:r,timestamp:Date.now()};e.history.push(l);}recalculateAnalysis(e){let t=this.calculateLevels(e.nodes);for(let s=0;s<t.length;s++)for(let n of t[s]){let r=e.nodes.get(n);r&&(r.level=s);}e.analysis={levels:t,maxParallelism:Math.max(...t.map(s=>s.length),0),criticalPath:this.calculateCriticalPath(e.nodes,t),estimatedTotalTime:this.calculateEstimatedTime(e.nodes,t)};}getDAG(e){return this.dags.get(e)}getReadyNodes(e){let t=this.dags.get(e);if(!t)return [];let s=[];for(let n of t.nodes.values()){if(n.status!=="pending")continue;n.dependencies.every(i=>t.nodes.get(i)?.status==="completed")&&s.push(n);}return s}updateNodeStatus(e,t,s,n,r){let i=this.dags.get(e);if(!i)return false;let o=i.nodes.get(t);return o?(o.status=s,s==="running"?o.startedAt=Date.now():(s==="completed"||s==="failed")&&(o.completedAt=Date.now()),n&&(o.result=n),r&&(o.error=r),this.emit("node_status_changed",{dagId:e,nodeId:t,status:s,result:n,error:r}),true):false}cloneDAG(e,t){let s=this.dags.get(e);if(!s)return null;let n=t??`${e}-clone-${Date.now()}`,r=new Map;for(let[o,l]of s.nodes)r.set(o,{...l});let i={...s,id:n,nodes:r,history:[...s.history],context:new Map(s.context),createdAt:Date.now()};return this.dags.set(n,i),this.emit("dag_cloned",{originalId:e,clonedId:n}),i}deleteDAG(e){let t=this.dags.delete(e);return t&&this.emit("dag_deleted",{dagId:e}),t}generateDAGId(e){return `dag-${e}-${++this.dagCounter}`}getStats(){let e=0,t=0;for(let s of this.dags.values())s.status==="executing"||s.status==="replanning"?e++:s.status==="completed"&&t++;return {totalDAGs:this.dags.size,activeDAGs:e,completedDAGs:t}}};function Fm(a){return new _c(a)}W();var jC={maxConcurrency:5,nodeTimeout:12e4,allowPartialFailure:true,retryCount:2,retryDelay:1e3,enablePeerReview:true,enableReplanning:true,maxReplanAttempts:3,progressUpdateInterval:1e3,collectDetailedMetrics:true,enableProgressiveExpansion:true},Rc=class extends EventEmitter{registry;dagBuilder;config;agentMatcher;progressiveManager;rgpsDataFlowManager;executionStates=new Map;progressTimers=new Map;currentAbortSignal;constructor(e,t,s){super(),this.registry=e,this.dagBuilder=t,this.agentMatcher=s?.agentMatcher,this.progressiveManager=s?.progressiveManager,this.rgpsDataFlowManager=s?.rgpsDataFlowManager,this.config={...jC,...s};}async execute(e,t){let s=this.dagBuilder.getDAG(e);if(!s)throw new Error(`DAG not found: ${e}`);this.currentAbortSignal=t;let n=this.initializeState(s);s.status="executing",s.startedAt=Date.now(),this.emit("execution_started",{dagId:e,nodeCount:s.nodes.size,levels:s.analysis.levels.length}),this.startProgressUpdates(e,s),this.rgpsDataFlowManager&&this.rgpsDataFlowManager.inferFromDAG(s);try{for(let i=0;i<s.analysis.levels.length&&!n.cancelled;i++){let o=s.analysis.levels[i];this.emit("level_started",{dagId:e,level:i,nodeIds:o}),await this.executeLevel(s,n,i,o),this.config.enableReplanning&&n.failedNodes.size>0&&await this.checkReplanCondition(s,n)&&n.replanCount<this.config.maxReplanAttempts&&await this.triggerReplan(s,n),this.emit("level_completed",{dagId:e,level:i,completedNodes:Array.from(n.completedNodes),failedNodes:Array.from(n.failedNodes)});}}finally{this.stopProgressUpdates(e);}let r=this.buildResult(s,n);return n.cancelled?s.status=n.cancelReason==="paused"?"paused":"cancelled":s.status=r.success?"completed":"failed",s.completedAt=Date.now(),this.executionStates.delete(e),this.emit("execution_completed",{dagId:e,result:r}),r}initializeState(e){let t={dagId:e.id,running:true,startedAt:Date.now(),runningNodes:new Set,completedNodes:new Set,failedNodes:new Set,skippedNodes:new Set,nodeResults:new Map,errors:[],replanCount:0,cancelled:false};for(let[s,n]of e.nodes){if(n.status==="completed"){t.completedNodes.add(s),n.result&&t.nodeResults.set(s,n.result);continue}if(n.status==="failed"){t.failedNodes.add(s),t.errors.push({nodeId:s,error:n.error||"Node failed previously",timestamp:Date.now()});continue}if(n.status==="skipped"){t.skippedNodes.add(s);continue}n.status==="running"&&this.dagBuilder.updateNodeStatus(e.id,s,"pending");}return this.executionStates.set(e.id,t),t}async executeLevel(e,t,s,n){let r=n.filter(o=>{let l=e.nodes.get(o);if(!l||l.status!=="pending")return false;let c=l.dependencies.every(d=>t.completedNodes.has(d));return l.dependencies.some(d=>t.failedNodes.has(d))&&!this.config.allowPartialFailure?(t.skippedNodes.add(o),this.dagBuilder.updateNodeStatus(e.id,o,"skipped"),false):c}),i=this.chunkArray(r,this.config.maxConcurrency);for(let o of i){if(t.cancelled)break;await Promise.all(o.map(l=>this.executeNode(e,t,l)));}}async executeNode(e,t,s){let n=e.nodes.get(s);if(n){t.runningNodes.add(s),this.dagBuilder.updateNodeStatus(e.id,s,"running"),this.emit("node_started",{dagId:e.id,nodeId:s,agentId:n.assignedAgent});try{let r=this.prepareContext(e,n),i=await this.runNode(n,r);if(t.runningNodes.delete(s),t.completedNodes.add(s),t.nodeResults.set(s,i),e.context.set(n.task.outputKey,i.output),i.data)for(let[o,l]of Object.entries(i.data))e.context.set(`${n.task.outputKey}.${o}`,l);this.rgpsDataFlowManager&&this.rgpsDataFlowManager.storeNodeOutput(s,n.task.outputKey,i.output),this.dagBuilder.updateNodeStatus(e.id,s,"completed",i),this.emit("node_completed",{dagId:e.id,nodeId:s,result:i}),this.config.enableProgressiveExpansion&&this.progressiveManager&&await this.checkProgressiveExpansion(e,n,i);}catch(r){let i=r instanceof Error?r.message:String(r);if(n.retryCount<n.maxRetries)return n.retryCount++,this.emit("node_retry",{dagId:e.id,nodeId:s,attempt:n.retryCount,error:i}),await new Promise(o=>setTimeout(o,this.config.retryDelay)),this.executeNode(e,t,s);t.runningNodes.delete(s),t.failedNodes.add(s),t.errors.push({nodeId:s,error:i,timestamp:Date.now()}),this.dagBuilder.updateNodeStatus(e.id,s,"failed",void 0,i),this.emit("node_failed",{dagId:e.id,nodeId:s,error:i,retries:n.retryCount});}}}prepareContext(e,t){let s={};for(let[n,r]of Object.entries(t.task.inputMapping))s[n]=e.context.get(r);for(let n of t.dependencies){let r=e.nodes.get(n);r&&(s[`dep_${n}`]=e.context.get(r.task.outputKey));}return {inputs:s,dagContext:e.context,timeout:this.config.nodeTimeout,abortSignal:this.currentAbortSignal}}async runNode(e,t){let s=Date.now(),n=this.registry.getInstance(e.assignedAgent);if(!n&&this.agentMatcher){m.info("DAG_EXECUTOR","Agent not found, using matcher",{nodeId:e.id,assignedAgent:e.assignedAgent});let d=await this.agentMatcher.matchOrCreate({subtask:{id:e.id,description:e.task.description,dependencies:e.dependencies,estimatedTime:e.task.estimatedTime??6e4,estimatedTokens:e.task.estimatedTokens??5e3,requiredCapabilities:e.task.requiredCapabilities},requiredCapabilities:e.task.requiredCapabilities});n=d.agent,e.assignedAgent=n.id,this.emit("agent_matched",{nodeId:e.id,agentId:n.id,isNewlyCreated:d.isNewlyCreated,score:d.score});}if(!n)throw new Error(`Agent not found: ${e.assignedAgent}`);let r=this.buildTaskDescription(e,t),i=d=>{d.agentId===n.id&&this.emit("node_text",{nodeId:e.id,agentId:d.agentId,text:d.text});},o=d=>{d.agentId===n.id&&this.emit("node_tool_start",{nodeId:e.id,agentId:d.agentId,tool:d.tool,toolId:d.toolId,args:d.args,targetPath:d.targetPath,description:d.description});},l=d=>{d.agentId===n.id&&this.emit("node_tool_end",{nodeId:e.id,agentId:d.agentId,tool:d.tool,toolId:d.toolId,success:d.success,output:d.output,outputTruncated:d.outputTruncated,args:d.args,summary:d.summary,duration:d.duration});};n.on("task_text",i),n.on("task_tool_start",o),n.on("task_tool_end",l);let c=await Promise.race([n.executeTask(r,void 0,void 0,{abortSignal:t.abortSignal}),this.createTimeout(t.timeout,e.id)]).finally(()=>{n.off("task_text",i),n.off("task_tool_start",o),n.off("task_tool_end",l);}),u=Date.now()-s;return {output:c.output,data:c.data,tokenUsage:c.tokenUsage??{input:0,output:0,total:0},duration:u,toolCalls:c.toolCalls}}buildTaskDescription(e,t){if(this.rgpsDataFlowManager)return this.rgpsDataFlowManager.buildTaskDescription(e.id,e.task.description);let s=e.task.description;if(Object.keys(t.inputs).length>0){s+=`
3196
3196
 
3197
3197
  ## \u8F93\u5165\u6570\u636E
3198
3198
  `;for(let[n,r]of Object.entries(t.inputs))r!==void 0&&(s+=`- ${n}: ${JSON.stringify(r)}
3199
3199
  `);}return s}createTimeout(e,t){return new Promise((s,n)=>{setTimeout(()=>{n(new Error(`Node ${t} execution timeout after ${e}ms`));},e);})}async checkReplanCondition(e,t){if(t.failedNodes.size/e.nodes.size>.3)return true;for(let n of e.analysis.criticalPath)if(t.failedNodes.has(n))return true;return false}async triggerReplan(e,t){t.replanCount++,e.status="replanning";let s={type:"node_failure",reason:`${t.failedNodes.size} nodes failed`,failedNodeId:Array.from(t.failedNodes)[0],error:t.errors[t.errors.length-1]?.error,timestamp:Date.now()};this.emit("replan_triggered",{dagId:e.id,trigger:s,attempt:t.replanCount}),this.emit("replan_required",{dagId:e.id,trigger:s,failedNodes:Array.from(t.failedNodes),completedNodes:Array.from(t.completedNodes)});}buildResult(e,t){let s=Date.now()-t.startedAt,n={total:0,byNode:new Map,byAgent:new Map};for(let[o,l]of t.nodeResults){let c=l.tokenUsage.total;n.total+=c,n.byNode.set(o,c);let u=e.nodes.get(o);if(u){let d=n.byAgent.get(u.assignedAgent)??0;n.byAgent.set(u.assignedAgent,d+c);}}let r=this.buildFinalOutput(e,t),i=!t.cancelled&&(t.failedNodes.size===0||this.config.allowPartialFailure&&t.completedNodes.size>0);return {dagId:e.id,success:i,completedNodes:t.completedNodes.size,failedNodes:t.failedNodes.size,skippedNodes:t.skippedNodes.size,totalDuration:s,nodeResults:t.nodeResults,finalOutput:r,errors:t.errors,replanCount:t.replanCount,tokenStats:n}}buildFinalOutput(e,t){let s=[];for(let n of e.analysis.levels)for(let r of n){let i=t.nodeResults.get(r);i&&s.push(`## ${r}
3200
3200
  ${i.output}`);}return s.join(`
3201
3201
 
3202
- `)}startProgressUpdates(e,t){let s=setInterval(()=>{let n=this.getMetrics(e);n&&this.emit("progress_updated",{dagId:e,metrics:n});},this.config.progressUpdateInterval);this.progressTimers.set(e,s);}stopProgressUpdates(e){let t=this.progressTimers.get(e);t&&(clearInterval(t),this.progressTimers.delete(e));}getMetrics(e){let t=this.dagBuilder.getDAG(e),s=this.executionStates.get(e);if(!t||!s)return null;let n=t.nodes.size,r=s.completedNodes.size,i=s.runningNodes.size,o=s.failedNodes.size,l=n-r-i-o-s.skippedNodes.size,c=r/n*100,u=Date.now()-s.startedAt,p=(r>0?u/r:t.analysis.estimatedTotalTime/n)*l,h=0;for(let f=0;f<t.analysis.levels.length;f++)if(t.analysis.levels[f].some(y=>s.runningNodes.has(y))){h=f;break}let g=Array.from(s.runningNodes).map(f=>{let b=t.nodes.get(f);return {nodeId:f,agentId:b?.assignedAgent??"",progress:50}});return {dagId:e,progress:c,currentLevel:h,totalLevels:t.analysis.levels.length,completedNodes:r,runningNodes:i,pendingNodes:l,failedNodes:o,elapsedTime:u,estimatedRemainingTime:p,currentNodes:g,updatedAt:Date.now()}}cancel(e,t="User cancelled"){let s=this.executionStates.get(e);if(!s)return false;s.cancelled=true,s.cancelReason=t;let n=this.dagBuilder.getDAG(e);return n&&(n.status="cancelled"),this.emit("execution_cancelled",{dagId:e,reason:t}),true}pause(e){let t=this.dagBuilder.getDAG(e),s=this.executionStates.get(e);return !t||!s?false:(s.cancelled=true,s.cancelReason="paused",t.status="paused",this.emit("execution_paused",{dagId:e}),true)}async resume(e){let t=this.dagBuilder.getDAG(e),s=this.executionStates.get(e);return t?(s&&s.cancelReason==="paused"&&(s.cancelled=false,s.cancelReason=void 0,t.status="executing",this.emit("execution_resumed",{dagId:e})),this.execute(e)):null}async checkProgressiveExpansion(e,t,s){if(this.progressiveManager)try{let n=await this.progressiveManager.analyzeForExpansion(e.id,t.id,t.task.description,s.output);if(n&&n.length>0){let r=await this.progressiveManager.expandDAG({dagId:e.id,triggerNodeId:t.id,subtasks:n,reason:"Discovered during execution"});r.success&&this.emit("dag_expanded",{dagId:e.id,triggerNodeId:t.id,addedNodes:r.addedNodes});}}catch(n){m.warn("DAG_EXECUTOR","Progressive expansion check failed",{error:n instanceof Error?n.message:String(n)});}}chunkArray(e,t){let s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s}isExecuting(e){return this.executionStates.has(e)}get activeExecutionCount(){return this.executionStates.size}async insertUserRequirement(e,t){if(!this.progressiveManager)return {success:false,error:"Progressive manager not configured"};if(!this.dagBuilder.getDAG(e))return {success:false,error:`DAG not found: ${e}`};m.info("DAG_EXECUTOR","Inserting user requirement",{dagId:e,description:t.description.slice(0,50),priority:t.priority});let n=await this.progressiveManager.insertUserRequirement(e,t);return n.success&&n.addedNodes.length>0?(this.emit("user_requirement_inserted",{dagId:e,nodeId:n.addedNodes[0],description:t.description,priority:t.priority}),{success:true,nodeId:n.addedNodes[0]}):{success:false,error:n.error}}};function jm(a,e,t){return new Rc(a,e,t)}var BC={maxReplanAttempts:3,replanTimeout:6e4,enableSmartReplanning:true,failureThreshold:.3,llmCall:void 0},Ac=class extends EventEmitter{registry;dagBuilder;config;replanHistory=new Map;constructor(e,t,s){super(),this.registry=e,this.dagBuilder=t,this.config={...BC,...s};}setLlmCall(e){this.config.llmCall=e;}async handleTrigger(e,t,s){let n=this.dagBuilder.getDAG(e);if(!n)return {success:false,reason:"DAG not found",duration:0};let r=Date.now();this.emit("replan_started",{dagId:e,trigger:t});try{let i=await this.analyzeProblem(n,t,s),o=await this.generateSuggestions(n,t,i);if(o.length===0)return {success:!1,reason:"No viable replan strategy found",duration:Date.now()-r};let l=this.selectBestSuggestion(o),c=await this.executeReplan(n,l);return this.recordHistory(e,c),this.emit("replan_completed",{dagId:e,result:c,strategy:l.strategy}),c}catch(i){let o=i instanceof Error?i.message:String(i),l={success:false,reason:`Replan failed: ${o}`,duration:Date.now()-r};return this.emit("replan_failed",{dagId:e,error:o}),l}}async analyzeProblem(e,t,s){let n=s?.failedNodes??[],r=[...n];for(let c of e.nodes.values())for(let u of n)c.dependencies.includes(u)&&!r.includes(c.id)&&r.push(c.id);let i="unknown",o=t.reason,l="medium";switch(t.type){case "node_failure":i="execution_failure",l=r.length>e.nodes.size*.3?"high":"medium";break;case "agent_unavailable":i="resource_failure",o=`Agent ${t.agentId} is unavailable`,l="high";break;case "timeout":i="timeout_failure",l="medium";break;case "resource_shortage":i="resource_failure",l="high";break;case "dependency_discovered":i="dependency_issue",l="low";break;case "scope_change":i="scope_change",l="medium";break;case "user_request":i="user_intervention",l="low";break}for(let c of e.analysis.criticalPath)if(r.includes(c)){l=l==="low"?"medium":l==="medium"?"high":"critical";break}return {failureType:i,rootCause:o,impactedNodes:r,severity:l}}async generateSuggestions(e,t,s){let n=[];if(t.type==="node_failure"||t.type==="timeout"){let r=t.failedNodeId?e.nodes.get(t.failedNodeId):null;r&&r.retryCount<r.maxRetries&&n.push({strategy:"retry",affectedNodes:[t.failedNodeId],actions:[{type:"modify",nodeId:t.failedNodeId,data:{status:"pending",retryCount:r.retryCount}}],confidence:.6,rationale:"Simple retry may resolve transient failures"});}if(t.type==="agent_unavailable"||t.type==="node_failure"){let r=t.failedNodeId??t.agentId;if(r){let i=await this.findAlternativeAgents(e,r);i.length>0&&n.push({strategy:"reassign",affectedNodes:s.impactedNodes,actions:s.impactedNodes.map(o=>({type:"reassign",nodeId:o,data:{newAgent:i[0]}})),confidence:.75,rationale:`Reassign to alternative agent: ${i[0]}`});}}if(this.canSkipNodes(e,s.impactedNodes)&&n.push({strategy:"skip",affectedNodes:s.impactedNodes,actions:s.impactedNodes.map(r=>({type:"modify",nodeId:r,data:{status:"skipped"}})),confidence:.5,rationale:"Skip non-critical failed nodes to continue execution"}),this.config.enableSmartReplanning&&this.config.llmCall){let r=await this.generateSmartSuggestion(e,t,s);r&&n.push(r);}return (s.severity==="high"||s.severity==="critical")&&n.push({strategy:"decompose",affectedNodes:s.impactedNodes,actions:s.impactedNodes.map(r=>({type:"modify",nodeId:r,data:{decompose:true}})),confidence:.65,rationale:"Decompose complex tasks into smaller subtasks"}),n}async findAlternativeAgents(e,t){let s=e.nodes.get(t);if(!s)return [];let n=s.assignedAgent,r=[],i=this.registry.listAll();for(let o of i)o.id!==n&&o.status==="idle"&&r.push(o.id);return r}canSkipNodes(e,t){for(let n of t)if(e.analysis.criticalPath.includes(n))return false;return Array.from(e.nodes.keys()).filter(n=>!t.includes(n)).length>0}async generateSmartSuggestion(e,t,s){if(!this.config.llmCall)return null;let n=`
3202
+ `)}startProgressUpdates(e,t){let s=setInterval(()=>{let n=this.getMetrics(e);n&&this.emit("progress_updated",{dagId:e,metrics:n});},this.config.progressUpdateInterval);this.progressTimers.set(e,s);}stopProgressUpdates(e){let t=this.progressTimers.get(e);t&&(clearInterval(t),this.progressTimers.delete(e));}getMetrics(e){let t=this.dagBuilder.getDAG(e),s=this.executionStates.get(e);if(!t||!s)return null;let n=t.nodes.size,r=s.completedNodes.size,i=s.runningNodes.size,o=s.failedNodes.size,l=n-r-i-o-s.skippedNodes.size,c=r/n*100,u=Date.now()-s.startedAt,p=(r>0?u/r:t.analysis.estimatedTotalTime/n)*l,h=0;for(let f=0;f<t.analysis.levels.length;f++)if(t.analysis.levels[f].some(y=>s.runningNodes.has(y))){h=f;break}let g=Array.from(s.runningNodes).map(f=>{let b=t.nodes.get(f);return {nodeId:f,agentId:b?.assignedAgent??"",progress:50}});return {dagId:e,progress:c,currentLevel:h,totalLevels:t.analysis.levels.length,completedNodes:r,runningNodes:i,pendingNodes:l,failedNodes:o,elapsedTime:u,estimatedRemainingTime:p,currentNodes:g,updatedAt:Date.now()}}cancel(e,t="User cancelled"){let s=this.executionStates.get(e);if(!s)return false;s.cancelled=true,s.cancelReason=t;let n=this.dagBuilder.getDAG(e);return n&&(n.status="cancelled"),this.emit("execution_cancelled",{dagId:e,reason:t}),true}pause(e){let t=this.dagBuilder.getDAG(e),s=this.executionStates.get(e);return !t||!s?false:(s.cancelled=true,s.cancelReason="paused",t.status="paused",this.emit("execution_paused",{dagId:e}),true)}async resume(e){let t=this.dagBuilder.getDAG(e),s=this.executionStates.get(e);return t?(s&&s.cancelReason==="paused"&&(s.cancelled=false,s.cancelReason=void 0,t.status="executing",this.emit("execution_resumed",{dagId:e})),this.execute(e)):null}async checkProgressiveExpansion(e,t,s){if(this.progressiveManager)try{let n=await this.progressiveManager.analyzeForExpansion(e.id,t.id,t.task.description,s.output);if(n&&n.length>0){let r=await this.progressiveManager.expandDAG({dagId:e.id,triggerNodeId:t.id,subtasks:n,reason:"Discovered during execution"});r.success&&this.emit("dag_expanded",{dagId:e.id,triggerNodeId:t.id,addedNodes:r.addedNodes});}}catch(n){m.warn("DAG_EXECUTOR","Progressive expansion check failed",{error:n instanceof Error?n.message:String(n)});}}chunkArray(e,t){let s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s}isExecuting(e){return this.executionStates.has(e)}get activeExecutionCount(){return this.executionStates.size}async insertUserRequirement(e,t){if(!this.progressiveManager)return {success:false,error:"Progressive manager not configured"};if(!this.dagBuilder.getDAG(e))return {success:false,error:`DAG not found: ${e}`};m.info("DAG_EXECUTOR","Inserting user requirement",{dagId:e,description:t.description.slice(0,50),priority:t.priority});let n=await this.progressiveManager.insertUserRequirement(e,t);return n.success&&n.addedNodes.length>0?(this.emit("user_requirement_inserted",{dagId:e,nodeId:n.addedNodes[0],description:t.description,priority:t.priority}),{success:true,nodeId:n.addedNodes[0]}):{success:false,error:n.error}}};function jm(a,e,t){return new Rc(a,e,t)}var GC={maxReplanAttempts:3,replanTimeout:6e4,enableSmartReplanning:true,failureThreshold:.3,llmCall:void 0},Ac=class extends EventEmitter{registry;dagBuilder;config;replanHistory=new Map;constructor(e,t,s){super(),this.registry=e,this.dagBuilder=t,this.config={...GC,...s};}setLlmCall(e){this.config.llmCall=e;}async handleTrigger(e,t,s){let n=this.dagBuilder.getDAG(e);if(!n)return {success:false,reason:"DAG not found",duration:0};let r=Date.now();this.emit("replan_started",{dagId:e,trigger:t});try{let i=await this.analyzeProblem(n,t,s),o=await this.generateSuggestions(n,t,i);if(o.length===0)return {success:!1,reason:"No viable replan strategy found",duration:Date.now()-r};let l=this.selectBestSuggestion(o),c=await this.executeReplan(n,l);return this.recordHistory(e,c),this.emit("replan_completed",{dagId:e,result:c,strategy:l.strategy}),c}catch(i){let o=i instanceof Error?i.message:String(i),l={success:false,reason:`Replan failed: ${o}`,duration:Date.now()-r};return this.emit("replan_failed",{dagId:e,error:o}),l}}async analyzeProblem(e,t,s){let n=s?.failedNodes??[],r=[...n];for(let c of e.nodes.values())for(let u of n)c.dependencies.includes(u)&&!r.includes(c.id)&&r.push(c.id);let i="unknown",o=t.reason,l="medium";switch(t.type){case "node_failure":i="execution_failure",l=r.length>e.nodes.size*.3?"high":"medium";break;case "agent_unavailable":i="resource_failure",o=`Agent ${t.agentId} is unavailable`,l="high";break;case "timeout":i="timeout_failure",l="medium";break;case "resource_shortage":i="resource_failure",l="high";break;case "dependency_discovered":i="dependency_issue",l="low";break;case "scope_change":i="scope_change",l="medium";break;case "user_request":i="user_intervention",l="low";break}for(let c of e.analysis.criticalPath)if(r.includes(c)){l=l==="low"?"medium":l==="medium"?"high":"critical";break}return {failureType:i,rootCause:o,impactedNodes:r,severity:l}}async generateSuggestions(e,t,s){let n=[];if(t.type==="node_failure"||t.type==="timeout"){let r=t.failedNodeId?e.nodes.get(t.failedNodeId):null;r&&r.retryCount<r.maxRetries&&n.push({strategy:"retry",affectedNodes:[t.failedNodeId],actions:[{type:"modify",nodeId:t.failedNodeId,data:{status:"pending",retryCount:r.retryCount}}],confidence:.6,rationale:"Simple retry may resolve transient failures"});}if(t.type==="agent_unavailable"||t.type==="node_failure"){let r=t.failedNodeId??t.agentId;if(r){let i=await this.findAlternativeAgents(e,r);i.length>0&&n.push({strategy:"reassign",affectedNodes:s.impactedNodes,actions:s.impactedNodes.map(o=>({type:"reassign",nodeId:o,data:{newAgent:i[0]}})),confidence:.75,rationale:`Reassign to alternative agent: ${i[0]}`});}}if(this.canSkipNodes(e,s.impactedNodes)&&n.push({strategy:"skip",affectedNodes:s.impactedNodes,actions:s.impactedNodes.map(r=>({type:"modify",nodeId:r,data:{status:"skipped"}})),confidence:.5,rationale:"Skip non-critical failed nodes to continue execution"}),this.config.enableSmartReplanning&&this.config.llmCall){let r=await this.generateSmartSuggestion(e,t,s);r&&n.push(r);}return (s.severity==="high"||s.severity==="critical")&&n.push({strategy:"decompose",affectedNodes:s.impactedNodes,actions:s.impactedNodes.map(r=>({type:"modify",nodeId:r,data:{decompose:true}})),confidence:.65,rationale:"Decompose complex tasks into smaller subtasks"}),n}async findAlternativeAgents(e,t){let s=e.nodes.get(t);if(!s)return [];let n=s.assignedAgent,r=[],i=this.registry.listAll();for(let o of i)o.id!==n&&o.status==="idle"&&r.push(o.id);return r}canSkipNodes(e,t){for(let n of t)if(e.analysis.criticalPath.includes(n))return false;return Array.from(e.nodes.keys()).filter(n=>!t.includes(n)).length>0}async generateSmartSuggestion(e,t,s){if(!this.config.llmCall)return null;let n=`
3203
3203
  \u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u6267\u884C\u91CD\u89C4\u5212\u4E13\u5BB6\u3002\u8BF7\u5206\u6790\u4EE5\u4E0B\u6267\u884C\u5931\u8D25\u60C5\u51B5\uFF0C\u5E76\u63D0\u4F9B\u91CD\u89C4\u5212\u5EFA\u8BAE\u3002
3204
3204
 
3205
3205
  ## \u5F53\u524D DAG \u72B6\u6001
@@ -3231,7 +3231,7 @@ ${i.output}`);}return s.join(`
3231
3231
  "confidence": 0.8,
3232
3232
  "rationale": "\u5EFA\u8BAE\u7406\u7531"
3233
3233
  }
3234
- `;try{let i=(await this.config.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u6267\u884C\u91CD\u89C4\u5212\u4E13\u5BB6\uFF0C\u64C5\u957F\u5904\u7406\u590D\u6742\u4EFB\u52A1\u6267\u884C\u4E2D\u7684\u5931\u8D25\u548C\u5F02\u5E38\u3002",n)).match(/\{[\s\S]*\}/);if(i){let o=JSON.parse(i[0]);return {strategy:o.strategy,affectedNodes:s.impactedNodes,actions:o.actions,confidence:o.confidence??.7,rationale:o.rationale??"LLM-generated suggestion"}}}catch(r){this.emit("smart_replan_failed",{error:r});}return null}selectBestSuggestion(e){return e.sort((t,s)=>s.confidence-t.confidence),e[0]}async executeReplan(e,t){let s=Date.now(),n=[],r=[],i=[],o=[];try{for(let l of t.actions)switch(l.type){case "add":let c=this.dagBuilder.addNode(e.id,l.data,"replanning_engine");c&&r.push(c.id);break;case "remove":this.dagBuilder.removeNode(e.id,l.nodeId,"replanning_engine")&&i.push(l.nodeId);break;case "modify":e.nodes.get(l.nodeId)&&(l.data.status&&this.dagBuilder.updateNodeStatus(e.id,l.nodeId,l.data.status),n.push(l.nodeId));break;case "reassign":let d=e.nodes.get(l.nodeId);if(d&&l.data.newAgent){let p=d.assignedAgent;this.dagBuilder.reassignAgent(e.id,l.nodeId,l.data.newAgent,"replanning_engine")&&o.push({nodeId:l.nodeId,previousAgent:p,newAgent:l.data.newAgent});}break;case "reorder":l.data.dependencies&&(this.dagBuilder.reorderDependencies(e.id,l.nodeId,l.data.dependencies,"replanning_engine"),n.push(l.nodeId));break}return this.dagBuilder.recalculateAnalysis(e),{success:!0,reason:t.rationale,newVersion:e.version,modifiedNodes:n,addedNodes:r,removedNodes:i,reassignments:o,duration:Date.now()-s}}catch(l){return {success:false,reason:`Replan execution failed: ${l instanceof Error?l.message:String(l)}`,duration:Date.now()-s}}}recordHistory(e,t){this.replanHistory.has(e)||this.replanHistory.set(e,[]),this.replanHistory.get(e).push(t);}getHistory(e){return this.replanHistory.get(e)??[]}clearHistory(e){this.replanHistory.delete(e);}setLLMCall(e){this.config.llmCall=e;}shouldTriggerReplan(e,t,s){return this.getHistory(e).length>=this.config.maxReplanAttempts?false:t/s>=this.config.failureThreshold}};function Bm(a,e,t){return new Ac(a,e,t)}var UC={reviewersPerNode:2,reviewTimeout:6e4,enableAutoReview:true,minQualityThreshold:3,excludeSelfReview:true,llmCall:void 0},Ec=class extends EventEmitter{registry;config;pendingRequests=new Map;reviewStatuses=new Map;reviewResults=new Map;requestCounter=0;constructor(e,t){super(),this.registry=e,this.config={...UC,...t};}setLlmCall(e){this.config.llmCall=e;}async requestReview(e,t,s){let n=e.nodes.get(t);if(!n)throw new Error(`Node not found: ${t}`);let r=this.selectReviewers(e,n),i=[];for(let o of r){let l={id:this.generateRequestId(),dagId:e.id,nodeId:t,revieweeId:n.assignedAgent,reviewerId:o,result:s,taskDescription:n.task.description,requestedAt:Date.now()};this.pendingRequests.set(l.id,l),this.reviewStatuses.set(l.id,{requestId:l.id,status:"pending"}),i.push(l),this.emit("review_requested",{requestId:l.id,nodeId:t,reviewerId:o});}return i}selectReviewers(e,t){let s=[],n=new Set;this.config.excludeSelfReview&&n.add(t.assignedAgent);let r=t.level,i=[];for(let[l,c]of e.nodes){if(n.has(c.assignedAgent)||c.status!=="completed")continue;let d=1/(1+Math.abs(c.level-r));i.push({agentId:c.assignedAgent,priority:d});}i.sort((l,c)=>c.priority-l.priority);let o=new Set;for(let l of i)if(!o.has(l.agentId)&&(o.add(l.agentId),s.push(l.agentId),s.length>=this.config.reviewersPerNode))break;if(s.length<this.config.reviewersPerNode){let l=this.registry.listAll();for(let c of l)if(!n.has(c.id)&&!o.has(c.id)&&(s.push(c.id),o.add(c.id),s.length>=this.config.reviewersPerNode))break}return s.length===0&&s.push("__llm_auto_reviewer__"),s}async executeReview(e){let t=this.pendingRequests.get(e);if(!t)return null;let s=this.reviewStatuses.get(e);if(!s)return null;s.status="in_progress",this.emit("review_started",{requestId:e,nodeId:t.nodeId,reviewerId:t.reviewerId});try{let n;if(t.reviewerId==="__llm_auto_reviewer__")this.config.llmCall?n=await this.conductLLMReview(t):n=this.conductAutoReview(t);else {let r=this.registry.getInstance(t.reviewerId);r&&typeof r.conductPeerReview=="function"?n=await Promise.race([r.conductPeerReview(t),this.createTimeout(this.config.reviewTimeout)]):this.config.llmCall?n=await this.conductLLMReview(t):n=this.conductAutoReview(t);}return s.status="completed",s.result=n,this.reviewResults.has(t.nodeId)||this.reviewResults.set(t.nodeId,[]),this.reviewResults.get(t.nodeId).push(n),this.emit("review_completed",{requestId:e,result:n}),this.pendingRequests.delete(e),n}catch(n){let r=n instanceof Error?n.message:String(n);return s.status="failed",s.error=r,this.emit("review_failed",{requestId:e,error:r}),null}}async conductLLMReview(e){if(!this.config.llmCall)return this.conductAutoReview(e);let t=`
3234
+ `;try{let i=(await this.config.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u6267\u884C\u91CD\u89C4\u5212\u4E13\u5BB6\uFF0C\u64C5\u957F\u5904\u7406\u590D\u6742\u4EFB\u52A1\u6267\u884C\u4E2D\u7684\u5931\u8D25\u548C\u5F02\u5E38\u3002",n)).match(/\{[\s\S]*\}/);if(i){let o=JSON.parse(i[0]);return {strategy:o.strategy,affectedNodes:s.impactedNodes,actions:o.actions,confidence:o.confidence??.7,rationale:o.rationale??"LLM-generated suggestion"}}}catch(r){this.emit("smart_replan_failed",{error:r});}return null}selectBestSuggestion(e){return e.sort((t,s)=>s.confidence-t.confidence),e[0]}async executeReplan(e,t){let s=Date.now(),n=[],r=[],i=[],o=[];try{for(let l of t.actions)switch(l.type){case "add":let c=this.dagBuilder.addNode(e.id,l.data,"replanning_engine");c&&r.push(c.id);break;case "remove":this.dagBuilder.removeNode(e.id,l.nodeId,"replanning_engine")&&i.push(l.nodeId);break;case "modify":e.nodes.get(l.nodeId)&&(l.data.status&&this.dagBuilder.updateNodeStatus(e.id,l.nodeId,l.data.status),n.push(l.nodeId));break;case "reassign":let d=e.nodes.get(l.nodeId);if(d&&l.data.newAgent){let p=d.assignedAgent;this.dagBuilder.reassignAgent(e.id,l.nodeId,l.data.newAgent,"replanning_engine")&&o.push({nodeId:l.nodeId,previousAgent:p,newAgent:l.data.newAgent});}break;case "reorder":l.data.dependencies&&(this.dagBuilder.reorderDependencies(e.id,l.nodeId,l.data.dependencies,"replanning_engine"),n.push(l.nodeId));break}return this.dagBuilder.recalculateAnalysis(e),{success:!0,reason:t.rationale,newVersion:e.version,modifiedNodes:n,addedNodes:r,removedNodes:i,reassignments:o,duration:Date.now()-s}}catch(l){return {success:false,reason:`Replan execution failed: ${l instanceof Error?l.message:String(l)}`,duration:Date.now()-s}}}recordHistory(e,t){this.replanHistory.has(e)||this.replanHistory.set(e,[]),this.replanHistory.get(e).push(t);}getHistory(e){return this.replanHistory.get(e)??[]}clearHistory(e){this.replanHistory.delete(e);}setLLMCall(e){this.config.llmCall=e;}shouldTriggerReplan(e,t,s){return this.getHistory(e).length>=this.config.maxReplanAttempts?false:t/s>=this.config.failureThreshold}};function Bm(a,e,t){return new Ac(a,e,t)}var WC={reviewersPerNode:2,reviewTimeout:6e4,enableAutoReview:true,minQualityThreshold:3,excludeSelfReview:true,llmCall:void 0},Ec=class extends EventEmitter{registry;config;pendingRequests=new Map;reviewStatuses=new Map;reviewResults=new Map;requestCounter=0;constructor(e,t){super(),this.registry=e,this.config={...WC,...t};}setLlmCall(e){this.config.llmCall=e;}async requestReview(e,t,s){let n=e.nodes.get(t);if(!n)throw new Error(`Node not found: ${t}`);let r=this.selectReviewers(e,n),i=[];for(let o of r){let l={id:this.generateRequestId(),dagId:e.id,nodeId:t,revieweeId:n.assignedAgent,reviewerId:o,result:s,taskDescription:n.task.description,requestedAt:Date.now()};this.pendingRequests.set(l.id,l),this.reviewStatuses.set(l.id,{requestId:l.id,status:"pending"}),i.push(l),this.emit("review_requested",{requestId:l.id,nodeId:t,reviewerId:o});}return i}selectReviewers(e,t){let s=[],n=new Set;this.config.excludeSelfReview&&n.add(t.assignedAgent);let r=t.level,i=[];for(let[l,c]of e.nodes){if(n.has(c.assignedAgent)||c.status!=="completed")continue;let d=1/(1+Math.abs(c.level-r));i.push({agentId:c.assignedAgent,priority:d});}i.sort((l,c)=>c.priority-l.priority);let o=new Set;for(let l of i)if(!o.has(l.agentId)&&(o.add(l.agentId),s.push(l.agentId),s.length>=this.config.reviewersPerNode))break;if(s.length<this.config.reviewersPerNode){let l=this.registry.listAll();for(let c of l)if(!n.has(c.id)&&!o.has(c.id)&&(s.push(c.id),o.add(c.id),s.length>=this.config.reviewersPerNode))break}return s.length===0&&s.push("__llm_auto_reviewer__"),s}async executeReview(e){let t=this.pendingRequests.get(e);if(!t)return null;let s=this.reviewStatuses.get(e);if(!s)return null;s.status="in_progress",this.emit("review_started",{requestId:e,nodeId:t.nodeId,reviewerId:t.reviewerId});try{let n;if(t.reviewerId==="__llm_auto_reviewer__")this.config.llmCall?n=await this.conductLLMReview(t):n=this.conductAutoReview(t);else {let r=this.registry.getInstance(t.reviewerId);r&&typeof r.conductPeerReview=="function"?n=await Promise.race([r.conductPeerReview(t),this.createTimeout(this.config.reviewTimeout)]):this.config.llmCall?n=await this.conductLLMReview(t):n=this.conductAutoReview(t);}return s.status="completed",s.result=n,this.reviewResults.has(t.nodeId)||this.reviewResults.set(t.nodeId,[]),this.reviewResults.get(t.nodeId).push(n),this.emit("review_completed",{requestId:e,result:n}),this.pendingRequests.delete(e),n}catch(n){let r=n instanceof Error?n.message:String(n);return s.status="failed",s.error=r,this.emit("review_failed",{requestId:e,error:r}),null}}async conductLLMReview(e){if(!this.config.llmCall)return this.conductAutoReview(e);let t=`
3235
3235
  \u4F60\u662F\u4E00\u4E2A\u4EE3\u7801/\u4EFB\u52A1\u8BC4\u5BA1\u4E13\u5BB6\u3002\u8BF7\u8BC4\u5BA1\u4EE5\u4E0B\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u3002
3236
3236
 
3237
3237
  ## \u4EFB\u52A1\u63CF\u8FF0
@@ -3263,13 +3263,13 @@ ${e.result.output}
3263
3263
  "comments": "\u603B\u4F53\u8BC4\u4EF7",
3264
3264
  "suggestions": ["\u5EFA\u8BAE1", "\u5EFA\u8BAE2"]
3265
3265
  }
3266
- `;try{let n=(await this.config.llmCall("\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u4EE3\u7801\u8BC4\u5BA1\u4E13\u5BB6\uFF0C\u64C5\u957F\u8BC4\u4F30\u4EFB\u52A1\u6267\u884C\u8D28\u91CF\u3002",t)).match(/\{[\s\S]*\}/);if(n){let r=JSON.parse(n[0]);return {reviewerId:e.reviewerId,revieweeId:e.revieweeId,nodeIds:[e.nodeId],scores:r.scores,overallScore:r.overallScore??this.calculateOverallScore(r.scores),comments:r.comments??"",suggestions:r.suggestions??[],reviewedAt:Date.now()}}}catch(s){this.emit("llm_review_failed",{error:s});}return this.conductAutoReview(e)}conductAutoReview(e){let t={completeness:4,quality:3.5,efficiency:this.calculateEfficiencyScore(e.result),standards:3.5};e.result.output.length<100&&(t.completeness=2.5),e.result.output.length>1e3&&(t.quality=4);let s=this.calculateOverallScore(t);return {reviewerId:e.reviewerId,revieweeId:e.revieweeId,nodeIds:[e.nodeId],scores:t,overallScore:s,comments:"Auto-generated review based on execution metrics",suggestions:this.generateAutoSuggestions(e.result,t),reviewedAt:Date.now()}}calculateEfficiencyScore(e){let t=e.duration,s=e.tokenUsage.total,n=4;return t>6e4?n-=1:t>3e4&&(n-=.5),s>1e4?n-=1:s>5e3&&(n-=.5),Math.max(1,Math.min(5,n))}calculateOverallScore(e){let t={completeness:.35,quality:.3,efficiency:.2,standards:.15};return e.completeness*t.completeness+e.quality*t.quality+e.efficiency*t.efficiency+e.standards*t.standards}generateAutoSuggestions(e,t){let s=[];return t.completeness<3&&s.push("Consider providing more comprehensive output"),t.efficiency<3&&s.push("Optimize execution time and resource usage"),t.quality<3&&s.push("Improve output quality and clarity"),t.standards<3&&s.push("Follow best practices and coding standards"),s}async executeAllPendingReviews(){let e=new Map,t=Array.from(this.pendingRequests.keys()).map(async s=>{let n=await this.executeReview(s);e.set(s,n);});return await Promise.all(t),e}getAggregatedReview(e){let t=this.reviewResults.get(e);if(!t||t.length===0)return null;let s={completeness:0,quality:0,efficiency:0,standards:0},n=0;for(let d of t)s.completeness+=d.scores.completeness,s.quality+=d.scores.quality,s.efficiency+=d.scores.efficiency,s.standards+=d.scores.standards,n+=d.overallScore;let r=t.length;s.completeness/=r,s.quality/=r,s.efficiency/=r,s.standards/=r;let i=n/r,o=t.map(d=>d.comments),l=t.flatMap(d=>d.suggestions),c=new Map;for(let d of l)c.set(d,(c.get(d)??0)+1);let u=Array.from(c.entries()).filter(([d,p])=>p>=Math.ceil(t.length/2)).map(([d])=>d);return {nodeId:e,reviewCount:r,averageScore:i,averageScores:s,commonIssues:o.filter(d=>d.length>0),commonSuggestions:u,passed:i>=this.config.minQualityThreshold,reviews:t}}async reviewDAG(e){let t=new Map;this.clearAll();for(let[s,n]of e.nodes)n.status!=="completed"||!n.result||await this.requestReview(e,s,n.result);await this.executeAllPendingReviews();for(let s of e.nodes.keys()){let n=this.getAggregatedReview(s);n&&t.set(s,n);}return this.emit("dag_review_completed",{dagId:e.id,reviewedNodes:t.size}),t}updateAgentReputation(e,t){let s=this.registry.get(e);if(!s)return;let n=(t.overallScore-3)*.1;this.emit("reputation_update_suggested",{agentId:e,currentReputation:s.reputation,delta:n,reason:`Peer review score: ${t.overallScore.toFixed(2)}`});}createTimeout(e){return new Promise((t,s)=>{setTimeout(()=>{s(new Error(`Review timeout after ${e}ms`));},e);})}generateRequestId(){return `review-${Date.now()}-${++this.requestCounter}`}get pendingCount(){return this.pendingRequests.size}clearNodeReviews(e){this.reviewResults.delete(e);}clearAll(){this.pendingRequests.clear(),this.reviewStatuses.clear(),this.reviewResults.clear();}setLLMCall(e){this.config.llmCall=e;}};function Gm(a,e){return new Ec(a,e)}W();var qC={strictMode:false,autoInfer:true},Ic=class extends EventEmitter{config;nodeConfigs=new Map;dataStore=new Map;dagNodeIndex=new Map;constructor(e){super(),this.config={...qC,...e};}inferFromDAG(e){let t=new Set(e.nodes.keys()),s=this.dagNodeIndex.get(e.id);if(s)for(let n of s)t.has(n)||(this.nodeConfigs.delete(n),this.pruneNodeData(n));for(let[n,r]of e.nodes){let i=this.inferNodeConfig(r,e);this.nodeConfigs.set(n,i);}this.dagNodeIndex.set(e.id,t),m.info("RGPS_DATA_FLOW","Inferred data flow from DAG",{dagId:e.id,nodeCount:this.nodeConfigs.size}),this.emit("data_flow_inferred",{dagId:e.id});}inferNodeConfig(e,t){let s=[],n=[];for(let r of e.dependencies){let i=t.nodes.get(r);i&&s.push({targetKey:`input_from_${r}`,sourceNodeId:r,sourceOutputKey:i.task.outputKey,required:true});}return n.push({key:e.task.outputKey,description:`Output of ${e.id}`,type:"string",required:true}),{nodeId:e.id,inputs:s,outputs:n}}getNodeInputs(e){let t=this.nodeConfigs.get(e);if(!t)return {};let s={};for(let n of t.inputs){let r=`${n.sourceNodeId}:${n.sourceOutputKey}`,i=this.dataStore.get(r);if(i)s[n.targetKey]=i.value;else if(n.defaultValue!==void 0)s[n.targetKey]=n.defaultValue;else if(n.required&&this.config.strictMode)throw new Error(`Missing required input: ${n.targetKey}`)}return s}storeNodeOutput(e,t,s){let n=`${e}:${t}`,r={key:t,value:s,type:this.inferType(s),sourceNode:e,createdAt:Date.now()};this.dataStore.set(n,r),this.emit("output_stored",{nodeId:e,outputKey:t,dataKey:n});}inferType(e){return typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":Array.isArray(e)?"array":"object"}buildTaskDescription(e,t){let s=this.getNodeInputs(e);if(Object.keys(s).length===0)return t;let n=t;n+=`
3266
+ `;try{let n=(await this.config.llmCall("\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u4EE3\u7801\u8BC4\u5BA1\u4E13\u5BB6\uFF0C\u64C5\u957F\u8BC4\u4F30\u4EFB\u52A1\u6267\u884C\u8D28\u91CF\u3002",t)).match(/\{[\s\S]*\}/);if(n){let r=JSON.parse(n[0]);return {reviewerId:e.reviewerId,revieweeId:e.revieweeId,nodeIds:[e.nodeId],scores:r.scores,overallScore:r.overallScore??this.calculateOverallScore(r.scores),comments:r.comments??"",suggestions:r.suggestions??[],reviewedAt:Date.now()}}}catch(s){this.emit("llm_review_failed",{error:s});}return this.conductAutoReview(e)}conductAutoReview(e){let t={completeness:4,quality:3.5,efficiency:this.calculateEfficiencyScore(e.result),standards:3.5};e.result.output.length<100&&(t.completeness=2.5),e.result.output.length>1e3&&(t.quality=4);let s=this.calculateOverallScore(t);return {reviewerId:e.reviewerId,revieweeId:e.revieweeId,nodeIds:[e.nodeId],scores:t,overallScore:s,comments:"Auto-generated review based on execution metrics",suggestions:this.generateAutoSuggestions(e.result,t),reviewedAt:Date.now()}}calculateEfficiencyScore(e){let t=e.duration,s=e.tokenUsage.total,n=4;return t>6e4?n-=1:t>3e4&&(n-=.5),s>1e4?n-=1:s>5e3&&(n-=.5),Math.max(1,Math.min(5,n))}calculateOverallScore(e){let t={completeness:.35,quality:.3,efficiency:.2,standards:.15};return e.completeness*t.completeness+e.quality*t.quality+e.efficiency*t.efficiency+e.standards*t.standards}generateAutoSuggestions(e,t){let s=[];return t.completeness<3&&s.push("Consider providing more comprehensive output"),t.efficiency<3&&s.push("Optimize execution time and resource usage"),t.quality<3&&s.push("Improve output quality and clarity"),t.standards<3&&s.push("Follow best practices and coding standards"),s}async executeAllPendingReviews(){let e=new Map,t=Array.from(this.pendingRequests.keys()).map(async s=>{let n=await this.executeReview(s);e.set(s,n);});return await Promise.all(t),e}getAggregatedReview(e){let t=this.reviewResults.get(e);if(!t||t.length===0)return null;let s={completeness:0,quality:0,efficiency:0,standards:0},n=0;for(let d of t)s.completeness+=d.scores.completeness,s.quality+=d.scores.quality,s.efficiency+=d.scores.efficiency,s.standards+=d.scores.standards,n+=d.overallScore;let r=t.length;s.completeness/=r,s.quality/=r,s.efficiency/=r,s.standards/=r;let i=n/r,o=t.map(d=>d.comments),l=t.flatMap(d=>d.suggestions),c=new Map;for(let d of l)c.set(d,(c.get(d)??0)+1);let u=Array.from(c.entries()).filter(([d,p])=>p>=Math.ceil(t.length/2)).map(([d])=>d);return {nodeId:e,reviewCount:r,averageScore:i,averageScores:s,commonIssues:o.filter(d=>d.length>0),commonSuggestions:u,passed:i>=this.config.minQualityThreshold,reviews:t}}async reviewDAG(e){let t=new Map;this.clearAll();for(let[s,n]of e.nodes)n.status!=="completed"||!n.result||await this.requestReview(e,s,n.result);await this.executeAllPendingReviews();for(let s of e.nodes.keys()){let n=this.getAggregatedReview(s);n&&t.set(s,n);}return this.emit("dag_review_completed",{dagId:e.id,reviewedNodes:t.size}),t}updateAgentReputation(e,t){let s=this.registry.get(e);if(!s)return;let n=(t.overallScore-3)*.1;this.emit("reputation_update_suggested",{agentId:e,currentReputation:s.reputation,delta:n,reason:`Peer review score: ${t.overallScore.toFixed(2)}`});}createTimeout(e){return new Promise((t,s)=>{setTimeout(()=>{s(new Error(`Review timeout after ${e}ms`));},e);})}generateRequestId(){return `review-${Date.now()}-${++this.requestCounter}`}get pendingCount(){return this.pendingRequests.size}clearNodeReviews(e){this.reviewResults.delete(e);}clearAll(){this.pendingRequests.clear(),this.reviewStatuses.clear(),this.reviewResults.clear();}setLLMCall(e){this.config.llmCall=e;}};function Gm(a,e){return new Ec(a,e)}W();var zC={strictMode:false,autoInfer:true},Ic=class extends EventEmitter{config;nodeConfigs=new Map;dataStore=new Map;dagNodeIndex=new Map;constructor(e){super(),this.config={...zC,...e};}inferFromDAG(e){let t=new Set(e.nodes.keys()),s=this.dagNodeIndex.get(e.id);if(s)for(let n of s)t.has(n)||(this.nodeConfigs.delete(n),this.pruneNodeData(n));for(let[n,r]of e.nodes){let i=this.inferNodeConfig(r,e);this.nodeConfigs.set(n,i);}this.dagNodeIndex.set(e.id,t),m.info("RGPS_DATA_FLOW","Inferred data flow from DAG",{dagId:e.id,nodeCount:this.nodeConfigs.size}),this.emit("data_flow_inferred",{dagId:e.id});}inferNodeConfig(e,t){let s=[],n=[];for(let r of e.dependencies){let i=t.nodes.get(r);i&&s.push({targetKey:`input_from_${r}`,sourceNodeId:r,sourceOutputKey:i.task.outputKey,required:true});}return n.push({key:e.task.outputKey,description:`Output of ${e.id}`,type:"string",required:true}),{nodeId:e.id,inputs:s,outputs:n}}getNodeInputs(e){let t=this.nodeConfigs.get(e);if(!t)return {};let s={};for(let n of t.inputs){let r=`${n.sourceNodeId}:${n.sourceOutputKey}`,i=this.dataStore.get(r);if(i)s[n.targetKey]=i.value;else if(n.defaultValue!==void 0)s[n.targetKey]=n.defaultValue;else if(n.required&&this.config.strictMode)throw new Error(`Missing required input: ${n.targetKey}`)}return s}storeNodeOutput(e,t,s){let n=`${e}:${t}`,r={key:t,value:s,type:this.inferType(s),sourceNode:e,createdAt:Date.now()};this.dataStore.set(n,r),this.emit("output_stored",{nodeId:e,outputKey:t,dataKey:n});}inferType(e){return typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":Array.isArray(e)?"array":"object"}buildTaskDescription(e,t){let s=this.getNodeInputs(e);if(Object.keys(s).length===0)return t;let n=t;n+=`
3267
3267
 
3268
3268
  ## \u8F93\u5165\u6570\u636E (Ai)
3269
3269
  `;for(let[r,i]of Object.entries(s)){let o=typeof i=="string"?i.slice(0,500)+(i.length>500?"...":""):JSON.stringify(i,null,2).slice(0,500);n+=`### ${r}
3270
3270
  ${o}
3271
3271
 
3272
- `;}return n}setNodeConfig(e){this.nodeConfigs.set(e.nodeId,e);}getNodeConfig(e){return this.nodeConfigs.get(e)}pruneNodeData(e){let t=`${e}:`;for(let s of Array.from(this.dataStore.keys()))s.startsWith(t)&&this.dataStore.delete(s);}clear(){this.dataStore.clear(),this.nodeConfigs.clear(),this.dagNodeIndex.clear();}getAllData(){return new Map(this.dataStore)}transferData(e,t,s){let n=this.dataStore.get(`${e}:${s}`),r=this.nodeConfigs.get(t);if(!n)return {success:false,error:`Source data not found: ${e}:${s}`};let i=r?.inputs.find(o=>o.sourceNodeId===e&&o.sourceOutputKey===s);if(i?.expectedType&&n.type!==i.expectedType){let o=this.convertType(n.value,i.expectedType);return o.success?{success:true,data:o.value}:{success:false,error:`Type mismatch: expected ${i.expectedType}, got ${n.type}`}}return i?.validator&&!i.validator(n.value)?{success:false,error:`Validation failed for ${s}`}:{success:true,data:n.value}}convertType(e,t){try{switch(t){case "string":return {success:!0,value:String(e)};case "number":let s=Number(e);return {success:!isNaN(s),value:s};case "boolean":return {success:!0,value:!!e};case "array":if(Array.isArray(e))return {success:!0,value:e};if(typeof e=="string")try{let n=JSON.parse(e);if(Array.isArray(n))return {success:!0,value:n}}catch{}return {success:!1};case "object":if(typeof e=="object"&&e!==null)return {success:!0,value:e};if(typeof e=="string")try{return {success:!0,value:JSON.parse(e)}}catch{}return {success:!1};default:return {success:!1}}}catch{return {success:false}}}};function Um(a){return new Ic(a)}W();var Mc={maxExpansions:10,maxNodes:50,autoAssignAgent:true},HC=`\u5206\u6790\u4EE5\u4E0B\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\uFF0C\u5224\u65AD\u662F\u5426\u9700\u8981\u989D\u5916\u7684\u5B50\u4EFB\u52A1\u3002
3272
+ `;}return n}setNodeConfig(e){this.nodeConfigs.set(e.nodeId,e);}getNodeConfig(e){return this.nodeConfigs.get(e)}pruneNodeData(e){let t=`${e}:`;for(let s of Array.from(this.dataStore.keys()))s.startsWith(t)&&this.dataStore.delete(s);}clear(){this.dataStore.clear(),this.nodeConfigs.clear(),this.dagNodeIndex.clear();}getAllData(){return new Map(this.dataStore)}transferData(e,t,s){let n=this.dataStore.get(`${e}:${s}`),r=this.nodeConfigs.get(t);if(!n)return {success:false,error:`Source data not found: ${e}:${s}`};let i=r?.inputs.find(o=>o.sourceNodeId===e&&o.sourceOutputKey===s);if(i?.expectedType&&n.type!==i.expectedType){let o=this.convertType(n.value,i.expectedType);return o.success?{success:true,data:o.value}:{success:false,error:`Type mismatch: expected ${i.expectedType}, got ${n.type}`}}return i?.validator&&!i.validator(n.value)?{success:false,error:`Validation failed for ${s}`}:{success:true,data:n.value}}convertType(e,t){try{switch(t){case "string":return {success:!0,value:String(e)};case "number":let s=Number(e);return {success:!isNaN(s),value:s};case "boolean":return {success:!0,value:!!e};case "array":if(Array.isArray(e))return {success:!0,value:e};if(typeof e=="string")try{let n=JSON.parse(e);if(Array.isArray(n))return {success:!0,value:n}}catch{}return {success:!1};case "object":if(typeof e=="object"&&e!==null)return {success:!0,value:e};if(typeof e=="string")try{return {success:!0,value:JSON.parse(e)}}catch{}return {success:!1};default:return {success:!1}}}catch{return {success:false}}}};function Um(a){return new Ic(a)}W();var Mc={maxExpansions:10,maxNodes:50,autoAssignAgent:true},JC=`\u5206\u6790\u4EE5\u4E0B\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\uFF0C\u5224\u65AD\u662F\u5426\u9700\u8981\u989D\u5916\u7684\u5B50\u4EFB\u52A1\u3002
3273
3273
 
3274
3274
  ## \u5F53\u524D\u4EFB\u52A1
3275
3275
  {taskDescription}
@@ -3294,7 +3294,7 @@ ${o}
3294
3294
  }
3295
3295
 
3296
3296
  \u5982\u679C\u4E0D\u9700\u8981\uFF0C\u8F93\u51FA\uFF1A
3297
- {"needsExpansion": false}`,Pc=class extends EventEmitter{dagBuilder;agentMatcher;llmCall;maxExpansions;maxNodes;autoAssignAgent;expansionCounts=new Map;nodeCounter=0;constructor(e){super(),this.dagBuilder=e.dagBuilder,this.agentMatcher=e.agentMatcher,this.llmCall=e.llmCall,this.maxExpansions=e.maxExpansions??Mc.maxExpansions,this.maxNodes=e.maxNodes??Mc.maxNodes,this.autoAssignAgent=e.autoAssignAgent??Mc.autoAssignAgent;}setLlmCall(e){this.llmCall=e;}async expandDAG(e){let{dagId:t,triggerNodeId:s,subtasks:n,reason:r}=e;m.info("PROGRESSIVE_DAG","Expanding DAG",{dagId:t,triggerNodeId:s,subtaskCount:n.length});let i=this.checkExpansionLimits(t);if(!i.allowed)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:0,error:i.reason};let o=this.dagBuilder.getDAG(t);if(!o)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:0,error:`DAG not found: ${t}`};let l=[],c=[];try{for(let d of n){let p=await this.addSubtaskNode(o,d,s);p&&l.push(p);}let u=this.updateDependencies(o,l,n);return c.push(...u),c.length>0&&this.dagBuilder.recalculateAnalysis(o),this.incrementExpansionCount(t),this.emit("dag_expanded",{dagId:t,triggerNodeId:s,addedNodes:l,modifiedNodes:c,reason:r}),{success:!0,addedNodes:l,modifiedNodes:c,newVersion:o.version}}catch(u){let d=u instanceof Error?u.message:String(u);return m.error("PROGRESSIVE_DAG","Expansion failed",{error:d}),{success:false,addedNodes:l,modifiedNodes:c,newVersion:o.version,error:d}}}checkExpansionLimits(e){let t=this.dagBuilder.getDAG(e);return t?(this.expansionCounts.get(e)??0)>=this.maxExpansions?{allowed:false,reason:`Max expansions reached: ${this.maxExpansions}`}:t.nodes.size>=this.maxNodes?{allowed:false,reason:`Max nodes reached: ${this.maxNodes}`}:{allowed:true}:{allowed:false,reason:"DAG not found"}}async addSubtaskNode(e,t,s){let n=this.generateNodeId(),r=t.dependsOn??[s],i={id:n,task:{description:t.description,inputMapping:{},outputKey:`output_${n}`,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},assignedAgent:"",dependencies:r,level:0,maxRetries:2,mutable:true};if(this.autoAssignAgent&&this.agentMatcher){let l=await this.agentMatcher.matchOrCreate({subtask:{id:n,description:t.description,dependencies:r,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},requiredCapabilities:t.requiredCapabilities});i.assignedAgent=l.agent.id;}return this.dagBuilder.addNode(e.id,i,"progressive_manager")?n:null}updateDependencies(e,t,s){let n=[];for(let r=0;r<s.length;r++){let i=s[r],o=t[r];if(i.requiredBy?.length&&o)for(let l of i.requiredBy){let c=e.nodes.get(l);c&&!c.dependencies.includes(o)&&(c.dependencies.push(o),n.push(l));}}return n}async analyzeForExpansion(e,t,s,n){if(!this.llmCall)return null;let r=HC.replace("{taskDescription}",s).replace("{executionResult}",n);try{let o=(await this.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u5206\u6790\u4E13\u5BB6\uFF0C\u64C5\u957F\u8BC6\u522B\u9700\u8981\u989D\u5916\u5904\u7406\u7684\u5B50\u4EFB\u52A1\u3002",r)).match(/\{[\s\S]*\}/);if(!o)return null;let l=JSON.parse(o[0]);return l.needsExpansion?l.subtasks:null}catch(i){return m.warn("PROGRESSIVE_DAG","Analysis failed",{error:i}),null}}generateNodeId(){return `progressive-${++this.nodeCounter}-${Date.now()}`}incrementExpansionCount(e){let t=this.expansionCounts.get(e)??0;this.expansionCounts.set(e,t+1);}getExpansionCount(e){return this.expansionCounts.get(e)??0}resetExpansionCount(e){this.expansionCounts.delete(e);}getRemainingExpansions(e){let t=this.expansionCounts.get(e)??0;return Math.max(0,this.maxExpansions-t)}async insertUserRequirement(e,t){m.info("PROGRESSIVE_DAG","Inserting user requirement",{dagId:e,description:t.description.slice(0,100),priority:t.priority});let s=this.dagBuilder.getDAG(e);if(!s)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:0,error:`DAG not found: ${e}`};let n=this.checkExpansionLimits(e);if(!n.allowed)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:s.version,error:n.reason};try{let r=await this.analyzeInsertionPoint(s,t),i=this.generateNodeId(),o={id:i,task:{description:t.description,inputMapping:{},outputKey:`output_${i}`,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},assignedAgent:"",dependencies:r.dependencies,level:r.level,maxRetries:2,mutable:!0};if(this.autoAssignAgent&&this.agentMatcher){let u=await this.agentMatcher.matchOrCreate({subtask:{id:i,description:t.description,dependencies:r.dependencies,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},requiredCapabilities:t.requiredCapabilities});o.assignedAgent=u.agent.id;}if(!this.dagBuilder.addNode(s.id,o,"user_requirement"))return {success:!1,addedNodes:[],modifiedNodes:[],newVersion:s.version,error:"Failed to add node to DAG"};let c=this.updateDownstreamDependencies(s,i,r.affectedNodes,t.blocking??!1);return c.length>0&&this.dagBuilder.recalculateAnalysis(s),this.incrementExpansionCount(e),this.emit("user_requirement_inserted",{dagId:e,nodeId:i,description:t.description,priority:t.priority,modifiedNodes:c}),{success:!0,addedNodes:[i],modifiedNodes:c,newVersion:s.version}}catch(r){let i=r instanceof Error?r.message:String(r);return m.error("PROGRESSIVE_DAG","Insert failed",{error:i}),{success:false,addedNodes:[],modifiedNodes:[],newVersion:s.version,error:i}}}async analyzeInsertionPoint(e,t){if(t.insertAfter){let s=e.nodes.get(t.insertAfter);if(s){let n=t.insertBefore?[t.insertBefore]:this.findDownstreamNodes(e,t.insertAfter);return {dependencies:[t.insertAfter],level:s.level+1,affectedNodes:n}}}if(t.insertBefore){let s=e.nodes.get(t.insertBefore);if(s)return {dependencies:s.dependencies,level:s.level,affectedNodes:[t.insertBefore]}}return this.llmCall?this.llmAnalyzeInsertionPoint(e,t):this.priorityBasedInsertion(e,t.priority)}async llmAnalyzeInsertionPoint(e,t){let n=`\u5206\u6790\u4EE5\u4E0B DAG \u7ED3\u6784\uFF0C\u786E\u5B9A\u65B0\u9700\u6C42\u7684\u6700\u4F73\u63D2\u5165\u4F4D\u7F6E\u3002
3297
+ {"needsExpansion": false}`,Pc=class extends EventEmitter{dagBuilder;agentMatcher;llmCall;maxExpansions;maxNodes;autoAssignAgent;expansionCounts=new Map;nodeCounter=0;constructor(e){super(),this.dagBuilder=e.dagBuilder,this.agentMatcher=e.agentMatcher,this.llmCall=e.llmCall,this.maxExpansions=e.maxExpansions??Mc.maxExpansions,this.maxNodes=e.maxNodes??Mc.maxNodes,this.autoAssignAgent=e.autoAssignAgent??Mc.autoAssignAgent;}setLlmCall(e){this.llmCall=e;}async expandDAG(e){let{dagId:t,triggerNodeId:s,subtasks:n,reason:r}=e;m.info("PROGRESSIVE_DAG","Expanding DAG",{dagId:t,triggerNodeId:s,subtaskCount:n.length});let i=this.checkExpansionLimits(t);if(!i.allowed)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:0,error:i.reason};let o=this.dagBuilder.getDAG(t);if(!o)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:0,error:`DAG not found: ${t}`};let l=[],c=[];try{for(let d of n){let p=await this.addSubtaskNode(o,d,s);p&&l.push(p);}let u=this.updateDependencies(o,l,n);return c.push(...u),c.length>0&&this.dagBuilder.recalculateAnalysis(o),this.incrementExpansionCount(t),this.emit("dag_expanded",{dagId:t,triggerNodeId:s,addedNodes:l,modifiedNodes:c,reason:r}),{success:!0,addedNodes:l,modifiedNodes:c,newVersion:o.version}}catch(u){let d=u instanceof Error?u.message:String(u);return m.error("PROGRESSIVE_DAG","Expansion failed",{error:d}),{success:false,addedNodes:l,modifiedNodes:c,newVersion:o.version,error:d}}}checkExpansionLimits(e){let t=this.dagBuilder.getDAG(e);return t?(this.expansionCounts.get(e)??0)>=this.maxExpansions?{allowed:false,reason:`Max expansions reached: ${this.maxExpansions}`}:t.nodes.size>=this.maxNodes?{allowed:false,reason:`Max nodes reached: ${this.maxNodes}`}:{allowed:true}:{allowed:false,reason:"DAG not found"}}async addSubtaskNode(e,t,s){let n=this.generateNodeId(),r=t.dependsOn??[s],i={id:n,task:{description:t.description,inputMapping:{},outputKey:`output_${n}`,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},assignedAgent:"",dependencies:r,level:0,maxRetries:2,mutable:true};if(this.autoAssignAgent&&this.agentMatcher){let l=await this.agentMatcher.matchOrCreate({subtask:{id:n,description:t.description,dependencies:r,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},requiredCapabilities:t.requiredCapabilities});i.assignedAgent=l.agent.id;}return this.dagBuilder.addNode(e.id,i,"progressive_manager")?n:null}updateDependencies(e,t,s){let n=[];for(let r=0;r<s.length;r++){let i=s[r],o=t[r];if(i.requiredBy?.length&&o)for(let l of i.requiredBy){let c=e.nodes.get(l);c&&!c.dependencies.includes(o)&&(c.dependencies.push(o),n.push(l));}}return n}async analyzeForExpansion(e,t,s,n){if(!this.llmCall)return null;let r=JC.replace("{taskDescription}",s).replace("{executionResult}",n);try{let o=(await this.llmCall("\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u5206\u6790\u4E13\u5BB6\uFF0C\u64C5\u957F\u8BC6\u522B\u9700\u8981\u989D\u5916\u5904\u7406\u7684\u5B50\u4EFB\u52A1\u3002",r)).match(/\{[\s\S]*\}/);if(!o)return null;let l=JSON.parse(o[0]);return l.needsExpansion?l.subtasks:null}catch(i){return m.warn("PROGRESSIVE_DAG","Analysis failed",{error:i}),null}}generateNodeId(){return `progressive-${++this.nodeCounter}-${Date.now()}`}incrementExpansionCount(e){let t=this.expansionCounts.get(e)??0;this.expansionCounts.set(e,t+1);}getExpansionCount(e){return this.expansionCounts.get(e)??0}resetExpansionCount(e){this.expansionCounts.delete(e);}getRemainingExpansions(e){let t=this.expansionCounts.get(e)??0;return Math.max(0,this.maxExpansions-t)}async insertUserRequirement(e,t){m.info("PROGRESSIVE_DAG","Inserting user requirement",{dagId:e,description:t.description.slice(0,100),priority:t.priority});let s=this.dagBuilder.getDAG(e);if(!s)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:0,error:`DAG not found: ${e}`};let n=this.checkExpansionLimits(e);if(!n.allowed)return {success:false,addedNodes:[],modifiedNodes:[],newVersion:s.version,error:n.reason};try{let r=await this.analyzeInsertionPoint(s,t),i=this.generateNodeId(),o={id:i,task:{description:t.description,inputMapping:{},outputKey:`output_${i}`,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},assignedAgent:"",dependencies:r.dependencies,level:r.level,maxRetries:2,mutable:!0};if(this.autoAssignAgent&&this.agentMatcher){let u=await this.agentMatcher.matchOrCreate({subtask:{id:i,description:t.description,dependencies:r.dependencies,estimatedTime:t.estimatedTime??6e4,estimatedTokens:5e3,requiredCapabilities:t.requiredCapabilities},requiredCapabilities:t.requiredCapabilities});o.assignedAgent=u.agent.id;}if(!this.dagBuilder.addNode(s.id,o,"user_requirement"))return {success:!1,addedNodes:[],modifiedNodes:[],newVersion:s.version,error:"Failed to add node to DAG"};let c=this.updateDownstreamDependencies(s,i,r.affectedNodes,t.blocking??!1);return c.length>0&&this.dagBuilder.recalculateAnalysis(s),this.incrementExpansionCount(e),this.emit("user_requirement_inserted",{dagId:e,nodeId:i,description:t.description,priority:t.priority,modifiedNodes:c}),{success:!0,addedNodes:[i],modifiedNodes:c,newVersion:s.version}}catch(r){let i=r instanceof Error?r.message:String(r);return m.error("PROGRESSIVE_DAG","Insert failed",{error:i}),{success:false,addedNodes:[],modifiedNodes:[],newVersion:s.version,error:i}}}async analyzeInsertionPoint(e,t){if(t.insertAfter){let s=e.nodes.get(t.insertAfter);if(s){let n=t.insertBefore?[t.insertBefore]:this.findDownstreamNodes(e,t.insertAfter);return {dependencies:[t.insertAfter],level:s.level+1,affectedNodes:n}}}if(t.insertBefore){let s=e.nodes.get(t.insertBefore);if(s)return {dependencies:s.dependencies,level:s.level,affectedNodes:[t.insertBefore]}}return this.llmCall?this.llmAnalyzeInsertionPoint(e,t):this.priorityBasedInsertion(e,t.priority)}async llmAnalyzeInsertionPoint(e,t){let n=`\u5206\u6790\u4EE5\u4E0B DAG \u7ED3\u6784\uFF0C\u786E\u5B9A\u65B0\u9700\u6C42\u7684\u6700\u4F73\u63D2\u5165\u4F4D\u7F6E\u3002
3298
3298
 
3299
3299
  ## \u5F53\u524D DAG \u8282\u70B9
3300
3300
  ${Array.from(e.nodes.entries()).map(([r,i])=>`- ${r}: ${i.task.description} (status: ${i.status})`).join(`
@@ -3308,7 +3308,7 @@ ${t.description}
3308
3308
  {
3309
3309
  "insertAfter": "\u5E94\u8BE5\u5728\u54EA\u4E2A\u8282\u70B9\u4E4B\u540E\u63D2\u5165",
3310
3310
  "reason": "\u539F\u56E0"
3311
- }`;try{let i=(await this.llmCall("\u4F60\u662F DAG \u8C03\u5EA6\u4E13\u5BB6\uFF0C\u64C5\u957F\u5206\u6790\u4EFB\u52A1\u4F9D\u8D56\u5173\u7CFB\u3002",n)).match(/\{[\s\S]*\}/);if(i){let o=JSON.parse(i[0]),l=e.nodes.get(o.insertAfter);if(l)return {dependencies:[o.insertAfter],level:l.level+1,affectedNodes:this.findDownstreamNodes(e,o.insertAfter)}}}catch{m.warn("PROGRESSIVE_DAG","LLM analysis failed, using priority-based");}return this.priorityBasedInsertion(e,t.priority)}priorityBasedInsertion(e,t){let s=[],n=[],r=[];for(let[i,o]of e.nodes)o.status==="running"?s.push(i):o.status==="pending"?n.push(i):o.status==="completed"&&r.push(i);if(t==="high"&&s.length>0)return {dependencies:s,level:Math.max(...s.map(i=>e.nodes.get(i).level))+1,affectedNodes:n};if(t==="low"){let i=Math.max(...Array.from(e.nodes.values()).map(l=>l.level));return {dependencies:Array.from(e.nodes.entries()).filter(([,l])=>l.level===i).map(([l])=>l),level:i+1,affectedNodes:[]}}if(r.length>0){let i=r[r.length-1],o=e.nodes.get(i);return {dependencies:[i],level:o.level+1,affectedNodes:n.slice(0,1)}}return {dependencies:[],level:0,affectedNodes:Array.from(e.nodes.keys())}}findDownstreamNodes(e,t){let s=[];for(let[n,r]of e.nodes)r.dependencies.includes(t)&&s.push(n);return s}updateDownstreamDependencies(e,t,s,n){let r=[];for(let i of s){let o=e.nodes.get(i);o&&o.status==="pending"&&n&&(o.dependencies.includes(t)||(o.dependencies.push(t),r.push(i)));}return r}};function Wm(a){return new Pc(a)}W();var Uo={minAvailability:.3,minReputation:2,allowDynamicCreation:true,maxAgents:20},KC={programmer:"programmer",coder:"programmer",developer:"programmer",reviewer:"reviewer",architect:"architect",tester:"tester",frontend:"frontend",backend:"backend",fullstack:"fullstack",devops:"devops",security:"security",documenter:"documenter",debugger:"debugger",data:"data",coordinator:"coordinator"},Dc=class extends EventEmitter{registry;factory;config;createdAgents=new Map;modelCapabilities;constructor(e,t,s){super(),this.registry=e,this.factory=t,this.config={minAvailability:s?.minAvailability??Uo.minAvailability,minReputation:s?.minReputation??Uo.minReputation,allowDynamicCreation:s?.allowDynamicCreation??Uo.allowDynamicCreation,maxAgents:s?.maxAgents??Uo.maxAgents},this.modelCapabilities=s?.modelCapabilities??new Map;}setModelCapabilities(e){this.modelCapabilities=e;}addModelCapability(e){this.modelCapabilities.set(e.modelId,e);}async matchOrCreate(e){let{subtask:t,requiredRole:s,requiredCapabilities:n}=e;m.debug("AGENT_MATCHER","Matching agent for subtask",{subtaskId:t.id,requiredRole:s,requiredCapabilities:n});let r=this.findBestMatch(e);if(r)return this.emit("agent_matched",{subtaskId:t.id,agentId:r.agent.id}),r;if(this.config.allowDynamicCreation){let o=this.createAgent(e);if(o)return this.emit("agent_created",{subtaskId:t.id,agentId:o.agent.id}),o}let i=this.findAnyAvailable();if(i)return i;throw new Error(`No agent available for subtask: ${t.id}`)}findBestMatch(e){let{requiredRole:t,requiredCapabilities:s,taskType:n,modelConstraints:r}=e,i=e.minAvailability??this.config.minAvailability,o=e.minReputation??this.config.minReputation,l=this.registry.getAll(),c=null;for(let u of l){if(u.availability<i||u.reputation<o||u.status!=="active")continue;let d=this.calculateScore(u,t,s,n,r);if(d.score>0&&(!c||d.score>c.score)){let p=this.registry.getInstance(u.id);p&&(c={agent:p,score:d.score,modelCapability:d.modelCapability,reasons:d.reasons});}}if(c){let u=c.modelCapability?c.modelCapability.cost.input+c.modelCapability.cost.output:void 0;return {agent:c.agent,isNewlyCreated:false,score:c.score,reason:c.reasons.join(", ")||"Matched existing agent",modelCapability:c.modelCapability,estimatedCost:u}}return null}calculateScore(e,t,s,n,r){let i=0,o=[];if(t&&e.role.name.toLowerCase().includes(t.toLowerCase())&&(i+=25,o.push(`\u89D2\u8272\u5339\u914D: ${t}`)),s?.length){let u=0;for(let p of s)e.capabilities.includes(p)&&u++;let d=u/s.length*25;i+=d,u>0&&o.push(`\u80FD\u529B\u5339\u914D: ${u}/${s.length}`);}i+=e.availability*15,i+=e.reputation/5*10;let l=e.metadata?.preferredModel,c;if(l&&this.modelCapabilities.size>0){if(c=this.modelCapabilities.get(l),c){if(r&&!this.checkModelConstraints(c,r))return {score:0,reasons:["\u6A21\u578B\u4E0D\u6EE1\u8DB3\u7EA6\u675F\u6761\u4EF6"]};if(n){let u=c.taskTypeScores[n]??.5;i+=u*25,u>=.7&&o.push(`\u6A21\u578B\u64C5\u957F ${n}`);}else i+=12.5;}}else i+=12.5;return {score:i,modelCapability:c,reasons:o}}checkModelConstraints(e,t){return !(t.maxCost!==void 0&&e.cost.input>t.maxCost||t.minContextWindow!==void 0&&e.contextWindow<t.minContextWindow||t.minReliability!==void 0&&e.performance.reliability<t.minReliability||t.requireTools&&!e.supportsTools||t.providerId&&e.providerId!==t.providerId||t.excludeModels?.includes(e.modelId))}createAgent(e){let{requiredRole:t,requiredCapabilities:s}=e;if(this.registry.getAll().length>=this.config.maxAgents)return m.warn("AGENT_MATCHER","Max agents reached"),null;let r=this.mapToRoleId(t);if(!r)return m.warn("AGENT_MATCHER","Unknown role",{requiredRole:t}),null;let i=this.factory.createFromRole(r,{additionalCapabilities:s});return this.registry.register(i),i.start(),this.createdAgents.set(i.id,i),m.info("AGENT_MATCHER","Created new agent",{agentId:i.id,role:r}),{agent:i,isNewlyCreated:true,score:100,reason:`Created new ${r} agent`}}mapToRoleId(e){if(!e)return "programmer";let t=e.toLowerCase();return KC[t]??"programmer"}findAnyAvailable(){let e=this.registry.getAll();for(let t of e)if(t.status==="active"&&t.availability>0){let s=this.registry.getInstance(t.id);if(s)return {agent:s,isNewlyCreated:false,score:1,reason:"Fallback to any available agent"}}return null}async matchAll(e){let t=new Map;for(let s of e){let n=await this.matchOrCreate({subtask:s,requiredCapabilities:s.requiredCapabilities});t.set(s.id,n);}return t}getCreatedAgents(){return Array.from(this.createdAgents.values())}};function qm(a,e,t){return new Dc(a,e,t)}var Lc=class extends EventEmitter{config;resourcePool=new Map;waitQueue=[];constructor(e){super(),this.config={maxConcurrency:e?.maxConcurrency??5,resourceWaitTimeout:e?.resourceWaitTimeout??6e4};}calculateCriticalPath(e){let t=this.forwardPass(e),s=this.backwardPass(e,t),n=new Map,r=[];for(let[l,c]of t){let u=s.get(l),d=u.LS-c.ES,p=d===0;n.set(l,{ES:c.ES,EF:c.EF,LS:u.LS,LF:u.LF,slack:d,isCritical:p}),p&&r.push(l);}let i=Math.max(...Array.from(t.values()).map(l=>l.EF)),o=this.analyzeParallelism(e,n);return {criticalPath:r,totalDuration:i,nodeSchedule:n,parallelismAnalysis:o}}forwardPass(e){let t=new Map,s=n=>{if(t.has(n))return t.get(n);let r=e.nodes.get(n);if(!r)return {ES:0,EF:0};let i=0;for(let c of r.dependencies){let u=s(c);i=Math.max(i,u.EF);}let o=r.task.estimatedTime??6e4,l=i+o;return t.set(n,{ES:i,EF:l}),{ES:i,EF:l}};for(let n of e.nodes.keys())s(n);return t}backwardPass(e,t){let s=new Map,n=Math.max(...Array.from(t.values()).map(o=>o.EF)),r=new Map;for(let[o,l]of e.nodes)r.set(o,[]);for(let[o,l]of e.nodes)for(let c of l.dependencies)r.get(c)?.push(o);let i=o=>{if(s.has(o))return s.get(o);let l=e.nodes.get(o);if(!l)return {LS:n,LF:n};let c=r.get(o)||[],u=n;for(let h of c){let g=i(h);u=Math.min(u,g.LS);}let d=l.task.estimatedTime??6e4,p=u-d;return s.set(o,{LS:p,LF:u}),{LS:p,LF:u}};for(let o of e.nodes.keys())i(o);return s}analyzeParallelism(e,t){let s=new Set;for(let l of t.values())s.add(l.ES),s.add(l.EF);let n=Array.from(s).sort((l,c)=>l-c),r=0,i=0;for(let l=0;l<n.length-1;l++){let c=n[l],u=0;for(let d of t.values())d.ES<=c&&c<d.EF&&u++;r=Math.max(r,u),i+=u;}let o=n.length>1?i/(n.length-1):0;return {maxParallelism:r,avgParallelism:o}}registerResource(e){this.resourcePool.set(e,{agentId:e,status:"available"}),this.emit("resource_registered",{agentId:e}),this.processWaitQueue();}async allocateResource(e,t){let s=this.findAvailableResource(t);return s?(s.status="busy",s.currentTask=e,s.allocatedAt=Date.now(),this.emit("resource_allocated",{agentId:s.agentId,nodeId:e}),s):this.waitForResource(e,t)}releaseResource(e){let t=this.resourcePool.get(e);t&&(t.status="available",t.currentTask=void 0,t.allocatedAt=void 0,this.emit("resource_released",{agentId:e}),this.processWaitQueue());}findAvailableResource(e){for(let t of this.resourcePool.values())if(t.status==="available")return t;return null}waitForResource(e,t){return new Promise((s,n)=>{let r=setTimeout(()=>{let i=this.waitQueue.findIndex(o=>o.nodeId===e);i>=0&&this.waitQueue.splice(i,1),n(new Error(`Resource wait timeout for ${e}`));},this.config.resourceWaitTimeout);this.waitQueue.push({nodeId:e,requirements:t,resolve:i=>{clearTimeout(r),s(i);},reject:i=>{clearTimeout(r),n(i);}});})}processWaitQueue(){if(this.waitQueue.length===0)return;let e=this.waitQueue[0],t=this.findAvailableResource(e.requirements);t&&(this.waitQueue.shift(),t.status="busy",t.currentTask=e.nodeId,t.allocatedAt=Date.now(),e.resolve(t));}getPoolStatus(){let e=0,t=0;for(let s of this.resourcePool.values())s.status==="available"?e++:s.status==="busy"&&t++;return {total:this.resourcePool.size,available:e,busy:t}}};function zm(a){return new Lc(a)}var Oc=class extends EventEmitter{capabilities=new Map;constructor(e){if(super(),e?.presetCapabilities)for(let t of e.presetCapabilities)this.register(t);}get(e){return this.capabilities.get(e)}register(e){this.capabilities.set(e.modelId,e),this.emit("model_registered",{modelId:e.modelId});}getAll(){return Array.from(this.capabilities.values())}findBestForTask(e,t){let s=this.filterByConstraints(t);if(s.length===0)return null;let n=null,r=-1;for(let i of s){let o=i.taskTypeScores[e]??.5;o>r&&(r=o,n=i);}return n}findByStrength(e){return this.getAll().filter(t=>t.strengths.some(s=>s.toLowerCase().includes(e.toLowerCase())))}filterByConstraints(e){return e?this.getAll().filter(t=>!(e.maxCost&&t.cost.input>e.maxCost||e.minContextWindow&&t.contextWindow<e.minContextWindow||e.minReliability&&t.performance.reliability<e.minReliability||e.requireTools&&!t.supportsTools||e.providerId&&t.providerId!==e.providerId||e.excludeModels?.includes(t.modelId))):this.getAll()}matchModel(e,t,s){let n=this.filterByConstraints(s);if(n.length===0)return null;let r=null;for(let i of n){let{score:o,reasons:l}=this.calculateMatchScore(i,e,t);(!r||o>r.score)&&(r={model:i,score:o,reasons:l,estimatedCost:i.cost.input+i.cost.output});}return r}calculateMatchScore(e,t,s){let n=0,r=[],i=e.taskTypeScores[t]??.5;n+=i*40,i>=.8&&r.push(`\u64C5\u957F ${t} \u4EFB\u52A1`);let o=0;for(let u of s)e.strengths.some(d=>d.toLowerCase().includes(u.toLowerCase()))&&o++;let l=s.length>0?o/s.length:.5;n+=l*30,o>0&&r.push(`\u5339\u914D ${o}/${s.length} \u9879\u80FD\u529B`),n+=e.performance.reliability*15;let c=Math.max(0,1-(e.cost.input+e.cost.output)/.1);return n+=c*15,{score:n,reasons:r}}};function Hm(a){return new Oc(a)}W();var Rn=class extends EventEmitter{llmCall;config;registry;messageBus;biddingEngine;negotiationEngine;consensusBuilder;proposalGenerator;dagBuilder;dagExecutor;replanningEngine;peerReviewEngine;agentFactory;agentMatcher;rgpsDataFlowManager;progressiveManager;negotiationSummarizer;modelCapabilityRegistry;dagScheduler;agentSubscriptions=new Map;started=false;aborted=false;abortController=null;currentExecutingAgentId=null;currentDagId=null;executing=false;pendingUserMessages=[];currentPrompt=null;interruptedState=null;constructor(e){super(),this.llmCall=e.llmCall,this.config={minComplexityForNetwork:e.minComplexityForNetwork??4,minAgentsRequired:e.minAgentsRequired??2,biddingTimeout:e.biddingTimeout??3e4,negotiationTimeout:e.negotiationTimeout??6e4,executionTimeout:e.executionTimeout??3e5,maxNegotiationRounds:e.maxNegotiationRounds??3,maxReplanAttempts:e.maxReplanAttempts??3,consensusThreshold:e.consensusThreshold??.67,autoCreateDefaultAgents:e.autoCreateDefaultAgents??true,customRoles:e.customRoles},this.registry=Im(e.registryConfig),this.messageBus=Mm(e.messageBusConfig),this.biddingEngine=Pm(this.registry,this.messageBus,e.biddingConfig),this.negotiationEngine=Dm(this.registry,this.messageBus,{...e.negotiationConfig,llmCall:this.llmCall}),this.consensusBuilder=Lm(e.negotiationConfig),this.proposalGenerator=Nm(this.registry,{...e.negotiationConfig,llmCall:this.llmCall}),this.dagBuilder=Fm(e.dagBuilderConfig),this.replanningEngine=Bm(this.registry,this.dagBuilder,e.replanningConfig),this.peerReviewEngine=Gm(this.registry,e.peerReviewConfig),this.agentFactory=Am({...e.agentFactoryConfig,llmCall:this.llmCall,executionCapability:e.executionCapability}),this.agentMatcher=qm(this.registry,this.agentFactory),this.rgpsDataFlowManager=Um({strictMode:false,autoInfer:true}),this.progressiveManager=Wm({dagBuilder:this.dagBuilder,agentMatcher:this.agentMatcher,llmCall:this.llmCall,maxExpansions:10,maxNodes:50,autoAssignAgent:true}),this.dagExecutor=jm(this.registry,this.dagBuilder,{...e.dagExecutorConfig,rgpsDataFlowManager:this.rgpsDataFlowManager,agentMatcher:this.agentMatcher,progressiveManager:this.progressiveManager,enableProgressiveExpansion:true}),this.negotiationSummarizer=$m({llmCall:this.llmCall}),this.modelCapabilityRegistry=Hm({presetCapabilities:e.presetModelCapabilities});let t=this.modelCapabilityRegistry.getAll();if(t.length>0){let s=new Map;for(let n of t)s.set(n.modelId,n);this.agentMatcher.setModelCapabilities(s);}this.dagScheduler=zm({maxConcurrency:e.dagSchedulerMaxConcurrency??5,resourceWaitTimeout:6e4}),this.setupEventListeners();}start(){if(this.started)return;this.started=true,this.registry.start(),this.config.autoCreateDefaultAgents&&this.createDefaultAgents(),this.subscribeExistingAgents();let e=this.registry.getStats();m.info("NETWORK",`Started with ${e.total} agents`,{active:e.active,busy:e.busy}),this.emitEvent({type:"runtime_started"});}stop(){this.started&&(this.started=false,this.registry.stop(),this.clearAgentSubscriptions(),this.cleanupEventListeners(),this.emitEvent({type:"runtime_stopped"}));}isExecuting(){return this.executing}getCurrentExecutingAgentId(){return this.currentExecutingAgentId}hasInterruptedState(){return this.interruptedState?this.dagBuilder.getDAG(this.interruptedState.dagId)!==null:false}getInterruptedStateSummary(){if(!this.interruptedState)return null;let e=this.dagBuilder.getDAG(this.interruptedState.dagId);if(!e)return null;let t=0,s=0,n=0;for(let r of e.nodes.values())if(r.status==="completed")t++;else if(r.status==="failed")s++;else {if(r.status==="skipped")continue;n++;}return {prompt:this.interruptedState.prompt,dagId:e.id,completedNodes:t,totalNodes:e.nodes.size,pendingNodes:n,failedNodes:s}}clearInterruptedState(){this.interruptedState=null;}markInterruptedState(e,t){let s=this.dagBuilder.getDAG(e);if(!s)return;if(this.interruptedState&&this.interruptedState.dagId===e){this.interruptedState={...this.interruptedState,interruptedAt:Date.now(),reason:t};return}let n=Array.from(new Set(Array.from(s.nodes.values()).map(r=>r.assignedAgent).filter(r=>!!r)));this.interruptedState={prompt:this.currentPrompt||"\u672A\u8BB0\u5F55\u539F\u59CB\u4EFB\u52A1",dagId:e,selectedAgentIds:n,negotiationRounds:0,interruptedAt:Date.now(),reason:t};}injectUserMessage(e){if(!this.executing)return m.warn("NETWORK","Cannot inject message: no task executing"),false;if(m.info("NETWORK","Injecting user message",{message:e.substring(0,100),currentAgentId:this.currentExecutingAgentId,currentDagId:this.currentDagId}),this.pendingUserMessages.push(e),this.currentExecutingAgentId){let t=this.registry.getInstance(this.currentExecutingAgentId);t&&typeof t.injectUserMessage=="function"&&(t.injectUserMessage(e),m.info("NETWORK","Message injected to agent",{agentId:this.currentExecutingAgentId}));}return this.emit("user_message_injected",{message:e,agentId:this.currentExecutingAgentId}),true}consumePendingUserMessages(){let e=[...this.pendingUserMessages];return this.pendingUserMessages=[],e}setCurrentExecutingAgent(e){this.currentExecutingAgentId=e;}cleanupEventListeners(){this.registry.removeAllListeners("agent_registered"),this.registry.removeAllListeners("agent_unregistered"),this.dagExecutor.removeAllListeners("node_started"),this.dagExecutor.removeAllListeners("node_completed"),this.dagExecutor.removeAllListeners("node_failed"),this.dagExecutor.removeAllListeners("replan_required"),this.replanningEngine.removeAllListeners("replan_started"),this.replanningEngine.removeAllListeners("replan_completed"),this.biddingEngine.removeAllListeners("bid_received"),this.progressiveManager.removeAllListeners("dag_expanded"),this.progressiveManager.removeAllListeners("user_requirement_inserted");}async chat(e,t){let s=Date.now();m.debug("NETWORK",">>> chat() started",{promptLength:e.prompt?.length}),this.aborted=false,this.abortController=new AbortController,this.executing=true,this.currentExecutingAgentId=null,this.currentDagId=null,this.currentPrompt=e.prompt,this.pendingUserMessages=[];let n=0,r=0,i=this.llmCall.bind(this),o=async(l,c,u)=>{let d={...u,signal:u?.signal||this.abortController?.signal},p=await i(l,c,d),h=Math.ceil((l.length+c.length)/4),g=Math.ceil(p.length/4);return n+=h,r+=g,t?.onTokenUsage?.({inputTokens:h,outputTokens:g,totalInputTokens:n,totalOutputTokens:r}),p};this.llmCall=o,this.progressiveManager.setLlmCall(o),this.negotiationSummarizer.setLlmCall(o),this.negotiationEngine.setLlmCall(o),this.proposalGenerator.setLlmCall(o),this.replanningEngine.setLlmCall(o),this.peerReviewEngine.setLlmCall(o);try{if(t?.onThinking?.("\u6B63\u5728\u5206\u6790\u4EFB\u52A1..."),this.aborted)throw new Error("Task aborted by user");m.debug("NETWORK",">>> Phase 1: analyzeTask starting");let l=await this.analyzeTask(e.prompt,e.context);if(this.aborted)throw new Error("Task aborted by user");m.debug("NETWORK",">>> Phase 1: analyzeTask completed",{complexity:l.complexity,requiresCollaboration:l.requiresCollaboration}),this.emitEvent({type:"task_analyzed",analysis:l}),t?.onAnalysis?.(l),m.debug("NETWORK",">>> Phase 2: selectMode starting");let c=this.selectMode(l);return m.debug("NETWORK",">>> Phase 2: selectMode completed",{mode:c.mode,reason:c.reason}),this.emitEvent({type:"mode_selected",mode:c.mode,reason:c.reason}),t?.onModeSelect?.(c.mode,c.reason,l.rawAnalysis),c.mode==="simple"?(m.debug("NETWORK",">>> Routing to executeSimpleMode"),this.executeSimpleMode(e,l,s,t)):c.mode==="pipeline"?this.executePipelineMode(e,l,s,c.reason,t):await this.executeNetworkMode(e,l,s,t)}catch(l){let c=l instanceof Error?l.message:String(l);throw c==="Network execution paused"?(m.info("NETWORK","Execution paused, waiting for resume"),l):(this.emitEvent({type:"chat_failed",error:c}),t?.onError?.(l instanceof Error?l:new Error(c)),l)}finally{this.llmCall=i,this.executing=false,this.currentExecutingAgentId=null,this.currentDagId=null,this.currentPrompt=null;}}async executeNetworkMode(e,t,s,n){if(this.aborted)throw new Error("Task aborted by user");n?.onThinking?.("\u6B63\u5728\u5E7F\u64AD\u4EFB\u52A1...");let r={id:`task-${Date.now()}`,description:t.description,userRequest:e.prompt,requiredCapabilities:t.requiredCapabilities,optionalCapabilities:t.optionalCapabilities,estimatedComplexity:t.complexity,priority:t.priority,tokenBudget:e.tokenBudget,context:e.context,broadcastedAt:Date.now(),bidDeadline:Date.now()+this.config.biddingTimeout};this.emitEvent({type:"task_broadcasted",task:r}),n?.onThinking?.("\u6B63\u5728\u6536\u96C6\u7ADE\u6807..."),n?.onBiddingStart?.(r.id),this.emitEvent({type:"bidding_started",taskId:r.id});let i=this.registry.getAll().map(C=>C.id),o=await this.biddingEngine.requestBidsFromAgents(r,i,{timeout:this.config.biddingTimeout,onAgentDecision:C=>{n?.onAgentBidDecision?.(C);}}),l=o.selectedAgents,c=o.bids,u=c.length>0?{agentId:c[0].agentId,confidence:c[0].confidence}:void 0;if(this.emitEvent({type:"bidding_completed",bids:c,selectedAgents:l}),n?.onBiddingComplete?.({taskId:r.id,totalBids:c.length,selectedAgents:l,topBid:u}),l.length<this.config.minAgentsRequired)return this.executePipelineMode(e,t,s,"\u7ADE\u6807 Agent \u6570\u91CF\u4E0D\u8DB3",n);this.emitEvent({type:"agents_selected",agentIds:l}),n?.onThinking?.("\u6B63\u5728\u534F\u5546\u6267\u884C\u8BA1\u5212..."),this.emitEvent({type:"negotiation_started",sessionId:r.id,participants:l}),n?.onNegotiation?.({sessionId:r.id,participants:l,status:"started"});let d=C=>{n?.onNegotiationMessage?.({sessionId:C.sessionId,agentId:C.message.from,type:C.message.type,content:C.message.content,round:C.message.round});};this.negotiationEngine.on("message_received",d);let p=await this.negotiationEngine.runFullNegotiation(r,l,c);this.negotiationEngine.off("message_received",d);let h={sessionId:r.id,success:p.success,proposal:p.proposal,participants:l,rounds:p.rounds,totalMessages:p.messageCount,duration:p.duration,failureReason:p.success?void 0:"Negotiation failed"};if(!h.success||!h.proposal)return this.emitEvent({type:"negotiation_failed",reason:h.failureReason??"\u672A\u80FD\u8FBE\u6210\u5171\u8BC6"}),n?.onNegotiation?.({sessionId:h.sessionId,participants:h.participants,status:"failed",rounds:h.rounds}),this.executePipelineMode(e,t,s,h.failureReason??"\u534F\u5546\u5931\u8D25",n);this.emitEvent({type:"consensus_reached",proposal:h.proposal}),n?.onNegotiation?.({sessionId:h.sessionId,participants:h.participants,status:"consensus",rounds:h.rounds});let g;if(p.session)try{g=await this.negotiationSummarizer.summarize(p.session);}catch(C){m.warn("NETWORK","Negotiation summary failed",{error:C instanceof Error?C.message:String(C)});}n?.onThinking?.("\u6B63\u5728\u6784\u5EFA\u6267\u884C\u8BA1\u5212...");let f=this.dagBuilder.createFromProposal(h.proposal);this.emitEvent({type:"dag_created",dag:f});let b=this.dagScheduler.calculateCriticalPath(f);m.debug("NETWORK","DAG scheduled",{dagId:f.id,criticalPathLength:b.criticalPath.length,estimatedDuration:b.totalDuration});let y=this.computeDAGLevels(f),w=[];for(let[C,k]of f.nodes)w.push({id:C,description:k.task?.description||C,agentId:k.assignedAgent||"unassigned",level:k.level,dependencies:k.dependencies||[]});return n?.onDAGCreated?.({id:f.id,nodeCount:f.nodes.size,levelCount:y.length,maxParallelism:Math.max(...y.map(C=>C.length),1),criticalPath:b.criticalPath,estimatedTime:b.totalDuration,nodes:w}),this.interruptedState={prompt:e.prompt,context:e.context,dagId:f.id,selectedAgentIds:l,negotiationRounds:h.rounds,negotiation:h,negotiationSummary:g,handlers:n,interruptedAt:Date.now()},this.executeDagAndFinalize(f,{startTime:s,selectedAgentIds:l,negotiation:h,negotiationRounds:h.rounds,negotiationSummary:g},n)}async executeDagAndFinalize(e,t,s){s?.onThinking?.("\u6B63\u5728\u6267\u884C\u4EFB\u52A1..."),this.emitEvent({type:"execution_started",dagId:e.id});let n=y=>{let w=e.nodes.get(y.nodeId);this.currentExecutingAgentId=y.agentId,this.currentDagId=y.dagId,s?.onNodeStart?.({nodeId:y.nodeId,agentId:y.agentId,description:w?.task?.description||""});},r=y=>{let w=e.nodes.get(y.nodeId);this.currentExecutingAgentId===w?.assignedAgent&&(this.currentExecutingAgentId=null);let C=this.formatNodeOutputPreview(y.result?.output||y.output||"");s?.onNodeComplete?.({nodeId:y.nodeId,agentId:w?.assignedAgent||"",description:w?.task?.description||"",output:C,duration:w?.completedAt&&w?.startedAt?w.completedAt-w.startedAt:0,tokenUsage:y.result?.tokenUsage}),this.updateProgress(e,s);},i=y=>{let w=e.nodes.get(y.nodeId);s?.onNodeFail?.({nodeId:y.nodeId,agentId:w?.assignedAgent||"",description:w?.task?.description||"",error:y.error}),this.updateProgress(e,s);},o=new Map,l=y=>{s?.onAgentText?.(y.agentId,y.text);},c=y=>{let w=y.toolId||`${y.agentId}-tool-${y.nodeId}`;o.set(y.agentId,w),s?.onToolStart?.({agentId:y.agentId,toolName:y.tool,toolId:w,args:y.args,targetPath:y.targetPath,description:y.description});},u=y=>{let w=y.toolId||o.get(y.agentId)||`${y.agentId}-tool-${y.nodeId}`;s?.onToolEnd?.({agentId:y.agentId,toolName:y.tool,toolId:w,success:y.success,output:y.output,outputTruncated:y.outputTruncated,args:y.args,summary:y.summary,duration:y.duration});},d=y=>{s?.onReplan?.({dagId:y.dagId,trigger:y.trigger.type,reason:y.trigger.reason,affectedNodes:y.trigger.failedNodeId?[y.trigger.failedNodeId]:[]});};this.dagExecutor.on("node_started",n),this.dagExecutor.on("node_completed",r),this.dagExecutor.on("node_failed",i),this.dagExecutor.on("node_text",l),this.dagExecutor.on("node_tool_start",c),this.dagExecutor.on("node_tool_end",u),this.replanningEngine.on("replan_started",d);let p;try{p=await this.dagExecutor.execute(e.id,this.abortController?.signal);}finally{this.dagExecutor.off("node_started",n),this.dagExecutor.off("node_completed",r),this.dagExecutor.off("node_failed",i),this.dagExecutor.off("node_text",l),this.dagExecutor.off("node_tool_start",c),this.dagExecutor.off("node_tool_end",u),this.replanningEngine.off("replan_started",d);}this.updateProgress(e,s),this.emitEvent({type:"execution_completed",result:p});let h=e.status;if(h==="paused"||h==="cancelled"||this.aborted){let y=p.errors[p.errors.length-1]?.error||"\u4EFB\u52A1\u5DF2\u6682\u505C";throw this.markInterruptedState(e.id,this.interruptedState?.reason||y),new Error("Network execution paused")}s?.onThinking?.("\u6B63\u5728\u8FDB\u884C\u4E92\u8BC4..."),this.emitEvent({type:"peer_review_started",dagId:e.id});let g=await this.conductPeerReviews(e,p);this.emitEvent({type:"peer_review_completed",summary:g}),s?.onPeerReview?.({reviewers:g.reputationUpdates.map(y=>y.agentId),averageScore:g.averageScore,summary:`${g.reviewCount} \u6B21\u8BC4\u5BA1\uFF0C\u5E73\u5747 ${g.averageScore.toFixed(1)}/5`});let f=await this.updateReputations(e,p,g);this.emitEvent({type:"reputation_updated",updates:f});let b={output:p.finalOutput??"",summary:{mode:"network",agentCount:t.selectedAgentIds.length,agents:t.selectedAgentIds,negotiationRounds:t.negotiationRounds,dagVersion:e.version,totalDuration:Date.now()-t.startTime,totalTokens:p.tokenStats?.total??0,successfulTasks:p.completedNodes,failedTasks:p.failedNodes},dag:e,negotiation:t.negotiation,negotiationSummary:t.negotiationSummary,peerReviews:g};return this.emitEvent({type:"chat_completed",response:b}),s?.onComplete?.(`\u6267\u884C\u5B8C\u6210: ${p.completedNodes}/${e.nodes.size} \u4EFB\u52A1\u6210\u529F`),s?.onText?.(b.output),this.interruptedState=null,b}formatNodeOutputPreview(e){if(!e)return "";let n=e.replace(/```[\s\S]*?```/g,"").replace(/\r\n/g,`
3311
+ }`;try{let i=(await this.llmCall("\u4F60\u662F DAG \u8C03\u5EA6\u4E13\u5BB6\uFF0C\u64C5\u957F\u5206\u6790\u4EFB\u52A1\u4F9D\u8D56\u5173\u7CFB\u3002",n)).match(/\{[\s\S]*\}/);if(i){let o=JSON.parse(i[0]),l=e.nodes.get(o.insertAfter);if(l)return {dependencies:[o.insertAfter],level:l.level+1,affectedNodes:this.findDownstreamNodes(e,o.insertAfter)}}}catch{m.warn("PROGRESSIVE_DAG","LLM analysis failed, using priority-based");}return this.priorityBasedInsertion(e,t.priority)}priorityBasedInsertion(e,t){let s=[],n=[],r=[];for(let[i,o]of e.nodes)o.status==="running"?s.push(i):o.status==="pending"?n.push(i):o.status==="completed"&&r.push(i);if(t==="high"&&s.length>0)return {dependencies:s,level:Math.max(...s.map(i=>e.nodes.get(i).level))+1,affectedNodes:n};if(t==="low"){let i=Math.max(...Array.from(e.nodes.values()).map(l=>l.level));return {dependencies:Array.from(e.nodes.entries()).filter(([,l])=>l.level===i).map(([l])=>l),level:i+1,affectedNodes:[]}}if(r.length>0){let i=r[r.length-1],o=e.nodes.get(i);return {dependencies:[i],level:o.level+1,affectedNodes:n.slice(0,1)}}return {dependencies:[],level:0,affectedNodes:Array.from(e.nodes.keys())}}findDownstreamNodes(e,t){let s=[];for(let[n,r]of e.nodes)r.dependencies.includes(t)&&s.push(n);return s}updateDownstreamDependencies(e,t,s,n){let r=[];for(let i of s){let o=e.nodes.get(i);o&&o.status==="pending"&&n&&(o.dependencies.includes(t)||(o.dependencies.push(t),r.push(i)));}return r}};function Wm(a){return new Pc(a)}W();var Uo={minAvailability:.3,minReputation:2,allowDynamicCreation:true,maxAgents:20},VC={programmer:"programmer",coder:"programmer",developer:"programmer",reviewer:"reviewer",architect:"architect",tester:"tester",frontend:"frontend",backend:"backend",fullstack:"fullstack",devops:"devops",security:"security",documenter:"documenter",debugger:"debugger",data:"data",coordinator:"coordinator"},Dc=class extends EventEmitter{registry;factory;config;createdAgents=new Map;modelCapabilities;constructor(e,t,s){super(),this.registry=e,this.factory=t,this.config={minAvailability:s?.minAvailability??Uo.minAvailability,minReputation:s?.minReputation??Uo.minReputation,allowDynamicCreation:s?.allowDynamicCreation??Uo.allowDynamicCreation,maxAgents:s?.maxAgents??Uo.maxAgents},this.modelCapabilities=s?.modelCapabilities??new Map;}setModelCapabilities(e){this.modelCapabilities=e;}addModelCapability(e){this.modelCapabilities.set(e.modelId,e);}async matchOrCreate(e){let{subtask:t,requiredRole:s,requiredCapabilities:n}=e;m.debug("AGENT_MATCHER","Matching agent for subtask",{subtaskId:t.id,requiredRole:s,requiredCapabilities:n});let r=this.findBestMatch(e);if(r)return this.emit("agent_matched",{subtaskId:t.id,agentId:r.agent.id}),r;if(this.config.allowDynamicCreation){let o=this.createAgent(e);if(o)return this.emit("agent_created",{subtaskId:t.id,agentId:o.agent.id}),o}let i=this.findAnyAvailable();if(i)return i;throw new Error(`No agent available for subtask: ${t.id}`)}findBestMatch(e){let{requiredRole:t,requiredCapabilities:s,taskType:n,modelConstraints:r}=e,i=e.minAvailability??this.config.minAvailability,o=e.minReputation??this.config.minReputation,l=this.registry.getAll(),c=null;for(let u of l){if(u.availability<i||u.reputation<o||u.status!=="active")continue;let d=this.calculateScore(u,t,s,n,r);if(d.score>0&&(!c||d.score>c.score)){let p=this.registry.getInstance(u.id);p&&(c={agent:p,score:d.score,modelCapability:d.modelCapability,reasons:d.reasons});}}if(c){let u=c.modelCapability?c.modelCapability.cost.input+c.modelCapability.cost.output:void 0;return {agent:c.agent,isNewlyCreated:false,score:c.score,reason:c.reasons.join(", ")||"Matched existing agent",modelCapability:c.modelCapability,estimatedCost:u}}return null}calculateScore(e,t,s,n,r){let i=0,o=[];if(t&&e.role.name.toLowerCase().includes(t.toLowerCase())&&(i+=25,o.push(`\u89D2\u8272\u5339\u914D: ${t}`)),s?.length){let u=0;for(let p of s)e.capabilities.includes(p)&&u++;let d=u/s.length*25;i+=d,u>0&&o.push(`\u80FD\u529B\u5339\u914D: ${u}/${s.length}`);}i+=e.availability*15,i+=e.reputation/5*10;let l=e.metadata?.preferredModel,c;if(l&&this.modelCapabilities.size>0){if(c=this.modelCapabilities.get(l),c){if(r&&!this.checkModelConstraints(c,r))return {score:0,reasons:["\u6A21\u578B\u4E0D\u6EE1\u8DB3\u7EA6\u675F\u6761\u4EF6"]};if(n){let u=c.taskTypeScores[n]??.5;i+=u*25,u>=.7&&o.push(`\u6A21\u578B\u64C5\u957F ${n}`);}else i+=12.5;}}else i+=12.5;return {score:i,modelCapability:c,reasons:o}}checkModelConstraints(e,t){return !(t.maxCost!==void 0&&e.cost.input>t.maxCost||t.minContextWindow!==void 0&&e.contextWindow<t.minContextWindow||t.minReliability!==void 0&&e.performance.reliability<t.minReliability||t.requireTools&&!e.supportsTools||t.providerId&&e.providerId!==t.providerId||t.excludeModels?.includes(e.modelId))}createAgent(e){let{requiredRole:t,requiredCapabilities:s}=e;if(this.registry.getAll().length>=this.config.maxAgents)return m.warn("AGENT_MATCHER","Max agents reached"),null;let r=this.mapToRoleId(t);if(!r)return m.warn("AGENT_MATCHER","Unknown role",{requiredRole:t}),null;let i=this.factory.createFromRole(r,{additionalCapabilities:s});return this.registry.register(i),i.start(),this.createdAgents.set(i.id,i),m.info("AGENT_MATCHER","Created new agent",{agentId:i.id,role:r}),{agent:i,isNewlyCreated:true,score:100,reason:`Created new ${r} agent`}}mapToRoleId(e){if(!e)return "programmer";let t=e.toLowerCase();return VC[t]??"programmer"}findAnyAvailable(){let e=this.registry.getAll();for(let t of e)if(t.status==="active"&&t.availability>0){let s=this.registry.getInstance(t.id);if(s)return {agent:s,isNewlyCreated:false,score:1,reason:"Fallback to any available agent"}}return null}async matchAll(e){let t=new Map;for(let s of e){let n=await this.matchOrCreate({subtask:s,requiredCapabilities:s.requiredCapabilities});t.set(s.id,n);}return t}getCreatedAgents(){return Array.from(this.createdAgents.values())}};function qm(a,e,t){return new Dc(a,e,t)}var Lc=class extends EventEmitter{config;resourcePool=new Map;waitQueue=[];constructor(e){super(),this.config={maxConcurrency:e?.maxConcurrency??5,resourceWaitTimeout:e?.resourceWaitTimeout??6e4};}calculateCriticalPath(e){let t=this.forwardPass(e),s=this.backwardPass(e,t),n=new Map,r=[];for(let[l,c]of t){let u=s.get(l),d=u.LS-c.ES,p=d===0;n.set(l,{ES:c.ES,EF:c.EF,LS:u.LS,LF:u.LF,slack:d,isCritical:p}),p&&r.push(l);}let i=Math.max(...Array.from(t.values()).map(l=>l.EF)),o=this.analyzeParallelism(e,n);return {criticalPath:r,totalDuration:i,nodeSchedule:n,parallelismAnalysis:o}}forwardPass(e){let t=new Map,s=n=>{if(t.has(n))return t.get(n);let r=e.nodes.get(n);if(!r)return {ES:0,EF:0};let i=0;for(let c of r.dependencies){let u=s(c);i=Math.max(i,u.EF);}let o=r.task.estimatedTime??6e4,l=i+o;return t.set(n,{ES:i,EF:l}),{ES:i,EF:l}};for(let n of e.nodes.keys())s(n);return t}backwardPass(e,t){let s=new Map,n=Math.max(...Array.from(t.values()).map(o=>o.EF)),r=new Map;for(let[o,l]of e.nodes)r.set(o,[]);for(let[o,l]of e.nodes)for(let c of l.dependencies)r.get(c)?.push(o);let i=o=>{if(s.has(o))return s.get(o);let l=e.nodes.get(o);if(!l)return {LS:n,LF:n};let c=r.get(o)||[],u=n;for(let h of c){let g=i(h);u=Math.min(u,g.LS);}let d=l.task.estimatedTime??6e4,p=u-d;return s.set(o,{LS:p,LF:u}),{LS:p,LF:u}};for(let o of e.nodes.keys())i(o);return s}analyzeParallelism(e,t){let s=new Set;for(let l of t.values())s.add(l.ES),s.add(l.EF);let n=Array.from(s).sort((l,c)=>l-c),r=0,i=0;for(let l=0;l<n.length-1;l++){let c=n[l],u=0;for(let d of t.values())d.ES<=c&&c<d.EF&&u++;r=Math.max(r,u),i+=u;}let o=n.length>1?i/(n.length-1):0;return {maxParallelism:r,avgParallelism:o}}registerResource(e){this.resourcePool.set(e,{agentId:e,status:"available"}),this.emit("resource_registered",{agentId:e}),this.processWaitQueue();}async allocateResource(e,t){let s=this.findAvailableResource(t);return s?(s.status="busy",s.currentTask=e,s.allocatedAt=Date.now(),this.emit("resource_allocated",{agentId:s.agentId,nodeId:e}),s):this.waitForResource(e,t)}releaseResource(e){let t=this.resourcePool.get(e);t&&(t.status="available",t.currentTask=void 0,t.allocatedAt=void 0,this.emit("resource_released",{agentId:e}),this.processWaitQueue());}findAvailableResource(e){for(let t of this.resourcePool.values())if(t.status==="available")return t;return null}waitForResource(e,t){return new Promise((s,n)=>{let r=setTimeout(()=>{let i=this.waitQueue.findIndex(o=>o.nodeId===e);i>=0&&this.waitQueue.splice(i,1),n(new Error(`Resource wait timeout for ${e}`));},this.config.resourceWaitTimeout);this.waitQueue.push({nodeId:e,requirements:t,resolve:i=>{clearTimeout(r),s(i);},reject:i=>{clearTimeout(r),n(i);}});})}processWaitQueue(){if(this.waitQueue.length===0)return;let e=this.waitQueue[0],t=this.findAvailableResource(e.requirements);t&&(this.waitQueue.shift(),t.status="busy",t.currentTask=e.nodeId,t.allocatedAt=Date.now(),e.resolve(t));}getPoolStatus(){let e=0,t=0;for(let s of this.resourcePool.values())s.status==="available"?e++:s.status==="busy"&&t++;return {total:this.resourcePool.size,available:e,busy:t}}};function zm(a){return new Lc(a)}var Oc=class extends EventEmitter{capabilities=new Map;constructor(e){if(super(),e?.presetCapabilities)for(let t of e.presetCapabilities)this.register(t);}get(e){return this.capabilities.get(e)}register(e){this.capabilities.set(e.modelId,e),this.emit("model_registered",{modelId:e.modelId});}getAll(){return Array.from(this.capabilities.values())}findBestForTask(e,t){let s=this.filterByConstraints(t);if(s.length===0)return null;let n=null,r=-1;for(let i of s){let o=i.taskTypeScores[e]??.5;o>r&&(r=o,n=i);}return n}findByStrength(e){return this.getAll().filter(t=>t.strengths.some(s=>s.toLowerCase().includes(e.toLowerCase())))}filterByConstraints(e){return e?this.getAll().filter(t=>!(e.maxCost&&t.cost.input>e.maxCost||e.minContextWindow&&t.contextWindow<e.minContextWindow||e.minReliability&&t.performance.reliability<e.minReliability||e.requireTools&&!t.supportsTools||e.providerId&&t.providerId!==e.providerId||e.excludeModels?.includes(t.modelId))):this.getAll()}matchModel(e,t,s){let n=this.filterByConstraints(s);if(n.length===0)return null;let r=null;for(let i of n){let{score:o,reasons:l}=this.calculateMatchScore(i,e,t);(!r||o>r.score)&&(r={model:i,score:o,reasons:l,estimatedCost:i.cost.input+i.cost.output});}return r}calculateMatchScore(e,t,s){let n=0,r=[],i=e.taskTypeScores[t]??.5;n+=i*40,i>=.8&&r.push(`\u64C5\u957F ${t} \u4EFB\u52A1`);let o=0;for(let u of s)e.strengths.some(d=>d.toLowerCase().includes(u.toLowerCase()))&&o++;let l=s.length>0?o/s.length:.5;n+=l*30,o>0&&r.push(`\u5339\u914D ${o}/${s.length} \u9879\u80FD\u529B`),n+=e.performance.reliability*15;let c=Math.max(0,1-(e.cost.input+e.cost.output)/.1);return n+=c*15,{score:n,reasons:r}}};function Hm(a){return new Oc(a)}W();var Rn=class extends EventEmitter{llmCall;config;registry;messageBus;biddingEngine;negotiationEngine;consensusBuilder;proposalGenerator;dagBuilder;dagExecutor;replanningEngine;peerReviewEngine;agentFactory;agentMatcher;rgpsDataFlowManager;progressiveManager;negotiationSummarizer;modelCapabilityRegistry;dagScheduler;agentSubscriptions=new Map;started=false;aborted=false;abortController=null;currentExecutingAgentId=null;currentDagId=null;executing=false;pendingUserMessages=[];currentPrompt=null;interruptedState=null;constructor(e){super(),this.llmCall=e.llmCall,this.config={minComplexityForNetwork:e.minComplexityForNetwork??4,minAgentsRequired:e.minAgentsRequired??2,biddingTimeout:e.biddingTimeout??3e4,negotiationTimeout:e.negotiationTimeout??6e4,executionTimeout:e.executionTimeout??3e5,maxNegotiationRounds:e.maxNegotiationRounds??3,maxReplanAttempts:e.maxReplanAttempts??3,consensusThreshold:e.consensusThreshold??.67,autoCreateDefaultAgents:e.autoCreateDefaultAgents??true,customRoles:e.customRoles},this.registry=Im(e.registryConfig),this.messageBus=Mm(e.messageBusConfig),this.biddingEngine=Pm(this.registry,this.messageBus,e.biddingConfig),this.negotiationEngine=Dm(this.registry,this.messageBus,{...e.negotiationConfig,llmCall:this.llmCall}),this.consensusBuilder=Lm(e.negotiationConfig),this.proposalGenerator=Nm(this.registry,{...e.negotiationConfig,llmCall:this.llmCall}),this.dagBuilder=Fm(e.dagBuilderConfig),this.replanningEngine=Bm(this.registry,this.dagBuilder,e.replanningConfig),this.peerReviewEngine=Gm(this.registry,e.peerReviewConfig),this.agentFactory=Am({...e.agentFactoryConfig,llmCall:this.llmCall,executionCapability:e.executionCapability}),this.agentMatcher=qm(this.registry,this.agentFactory),this.rgpsDataFlowManager=Um({strictMode:false,autoInfer:true}),this.progressiveManager=Wm({dagBuilder:this.dagBuilder,agentMatcher:this.agentMatcher,llmCall:this.llmCall,maxExpansions:10,maxNodes:50,autoAssignAgent:true}),this.dagExecutor=jm(this.registry,this.dagBuilder,{...e.dagExecutorConfig,rgpsDataFlowManager:this.rgpsDataFlowManager,agentMatcher:this.agentMatcher,progressiveManager:this.progressiveManager,enableProgressiveExpansion:true}),this.negotiationSummarizer=$m({llmCall:this.llmCall}),this.modelCapabilityRegistry=Hm({presetCapabilities:e.presetModelCapabilities});let t=this.modelCapabilityRegistry.getAll();if(t.length>0){let s=new Map;for(let n of t)s.set(n.modelId,n);this.agentMatcher.setModelCapabilities(s);}this.dagScheduler=zm({maxConcurrency:e.dagSchedulerMaxConcurrency??5,resourceWaitTimeout:6e4}),this.setupEventListeners();}start(){if(this.started)return;this.started=true,this.registry.start(),this.config.autoCreateDefaultAgents&&this.createDefaultAgents(),this.subscribeExistingAgents();let e=this.registry.getStats();m.info("NETWORK",`Started with ${e.total} agents`,{active:e.active,busy:e.busy}),this.emitEvent({type:"runtime_started"});}stop(){this.started&&(this.started=false,this.registry.stop(),this.clearAgentSubscriptions(),this.cleanupEventListeners(),this.emitEvent({type:"runtime_stopped"}));}isExecuting(){return this.executing}getCurrentExecutingAgentId(){return this.currentExecutingAgentId}hasInterruptedState(){return this.interruptedState?this.dagBuilder.getDAG(this.interruptedState.dagId)!==null:false}getInterruptedStateSummary(){if(!this.interruptedState)return null;let e=this.dagBuilder.getDAG(this.interruptedState.dagId);if(!e)return null;let t=0,s=0,n=0;for(let r of e.nodes.values())if(r.status==="completed")t++;else if(r.status==="failed")s++;else {if(r.status==="skipped")continue;n++;}return {prompt:this.interruptedState.prompt,dagId:e.id,completedNodes:t,totalNodes:e.nodes.size,pendingNodes:n,failedNodes:s}}clearInterruptedState(){this.interruptedState=null;}markInterruptedState(e,t){let s=this.dagBuilder.getDAG(e);if(!s)return;if(this.interruptedState&&this.interruptedState.dagId===e){this.interruptedState={...this.interruptedState,interruptedAt:Date.now(),reason:t};return}let n=Array.from(new Set(Array.from(s.nodes.values()).map(r=>r.assignedAgent).filter(r=>!!r)));this.interruptedState={prompt:this.currentPrompt||"\u672A\u8BB0\u5F55\u539F\u59CB\u4EFB\u52A1",dagId:e,selectedAgentIds:n,negotiationRounds:0,interruptedAt:Date.now(),reason:t};}injectUserMessage(e){if(!this.executing)return m.warn("NETWORK","Cannot inject message: no task executing"),false;if(m.info("NETWORK","Injecting user message",{message:e.substring(0,100),currentAgentId:this.currentExecutingAgentId,currentDagId:this.currentDagId}),this.pendingUserMessages.push(e),this.currentExecutingAgentId){let t=this.registry.getInstance(this.currentExecutingAgentId);t&&typeof t.injectUserMessage=="function"&&(t.injectUserMessage(e),m.info("NETWORK","Message injected to agent",{agentId:this.currentExecutingAgentId}));}return this.emit("user_message_injected",{message:e,agentId:this.currentExecutingAgentId}),true}consumePendingUserMessages(){let e=[...this.pendingUserMessages];return this.pendingUserMessages=[],e}setCurrentExecutingAgent(e){this.currentExecutingAgentId=e;}cleanupEventListeners(){this.registry.removeAllListeners("agent_registered"),this.registry.removeAllListeners("agent_unregistered"),this.dagExecutor.removeAllListeners("node_started"),this.dagExecutor.removeAllListeners("node_completed"),this.dagExecutor.removeAllListeners("node_failed"),this.dagExecutor.removeAllListeners("replan_required"),this.replanningEngine.removeAllListeners("replan_started"),this.replanningEngine.removeAllListeners("replan_completed"),this.biddingEngine.removeAllListeners("bid_received"),this.progressiveManager.removeAllListeners("dag_expanded"),this.progressiveManager.removeAllListeners("user_requirement_inserted");}async chat(e,t){let s=Date.now();m.debug("NETWORK",">>> chat() started",{promptLength:e.prompt?.length}),this.aborted=false,this.abortController=new AbortController,this.executing=true,this.currentExecutingAgentId=null,this.currentDagId=null,this.currentPrompt=e.prompt,this.pendingUserMessages=[];let n=0,r=0,i=this.llmCall.bind(this),o=async(l,c,u)=>{let d={...u,signal:u?.signal||this.abortController?.signal},p=await i(l,c,d),h=Math.ceil((l.length+c.length)/4),g=Math.ceil(p.length/4);return n+=h,r+=g,t?.onTokenUsage?.({inputTokens:h,outputTokens:g,totalInputTokens:n,totalOutputTokens:r}),p};this.llmCall=o,this.progressiveManager.setLlmCall(o),this.negotiationSummarizer.setLlmCall(o),this.negotiationEngine.setLlmCall(o),this.proposalGenerator.setLlmCall(o),this.replanningEngine.setLlmCall(o),this.peerReviewEngine.setLlmCall(o);try{if(t?.onThinking?.("\u6B63\u5728\u5206\u6790\u4EFB\u52A1..."),this.aborted)throw new Error("Task aborted by user");m.debug("NETWORK",">>> Phase 1: analyzeTask starting");let l=await this.analyzeTask(e.prompt,e.context);if(this.aborted)throw new Error("Task aborted by user");m.debug("NETWORK",">>> Phase 1: analyzeTask completed",{complexity:l.complexity,requiresCollaboration:l.requiresCollaboration}),this.emitEvent({type:"task_analyzed",analysis:l}),t?.onAnalysis?.(l),m.debug("NETWORK",">>> Phase 2: selectMode starting");let c=this.selectMode(l);return m.debug("NETWORK",">>> Phase 2: selectMode completed",{mode:c.mode,reason:c.reason}),this.emitEvent({type:"mode_selected",mode:c.mode,reason:c.reason}),t?.onModeSelect?.(c.mode,c.reason,l.rawAnalysis),c.mode==="simple"?(m.debug("NETWORK",">>> Routing to executeSimpleMode"),this.executeSimpleMode(e,l,s,t)):c.mode==="pipeline"?this.executePipelineMode(e,l,s,c.reason,t):await this.executeNetworkMode(e,l,s,t)}catch(l){let c=l instanceof Error?l.message:String(l);throw c==="Network execution paused"?(m.info("NETWORK","Execution paused, waiting for resume"),l):(this.emitEvent({type:"chat_failed",error:c}),t?.onError?.(l instanceof Error?l:new Error(c)),l)}finally{this.llmCall=i,this.executing=false,this.currentExecutingAgentId=null,this.currentDagId=null,this.currentPrompt=null;}}async executeNetworkMode(e,t,s,n){if(this.aborted)throw new Error("Task aborted by user");n?.onThinking?.("\u6B63\u5728\u5E7F\u64AD\u4EFB\u52A1...");let r={id:`task-${Date.now()}`,description:t.description,userRequest:e.prompt,requiredCapabilities:t.requiredCapabilities,optionalCapabilities:t.optionalCapabilities,estimatedComplexity:t.complexity,priority:t.priority,tokenBudget:e.tokenBudget,context:e.context,broadcastedAt:Date.now(),bidDeadline:Date.now()+this.config.biddingTimeout};this.emitEvent({type:"task_broadcasted",task:r}),n?.onThinking?.("\u6B63\u5728\u6536\u96C6\u7ADE\u6807..."),n?.onBiddingStart?.(r.id),this.emitEvent({type:"bidding_started",taskId:r.id});let i=this.registry.getAll().map(C=>C.id),o=await this.biddingEngine.requestBidsFromAgents(r,i,{timeout:this.config.biddingTimeout,onAgentDecision:C=>{n?.onAgentBidDecision?.(C);}}),l=o.selectedAgents,c=o.bids,u=c.length>0?{agentId:c[0].agentId,confidence:c[0].confidence}:void 0;if(this.emitEvent({type:"bidding_completed",bids:c,selectedAgents:l}),n?.onBiddingComplete?.({taskId:r.id,totalBids:c.length,selectedAgents:l,topBid:u}),l.length<this.config.minAgentsRequired)return this.executePipelineMode(e,t,s,"\u7ADE\u6807 Agent \u6570\u91CF\u4E0D\u8DB3",n);this.emitEvent({type:"agents_selected",agentIds:l}),n?.onThinking?.("\u6B63\u5728\u534F\u5546\u6267\u884C\u8BA1\u5212..."),this.emitEvent({type:"negotiation_started",sessionId:r.id,participants:l}),n?.onNegotiation?.({sessionId:r.id,participants:l,status:"started"});let d=C=>{n?.onNegotiationMessage?.({sessionId:C.sessionId,agentId:C.message.from,type:C.message.type,content:C.message.content,round:C.message.round});};this.negotiationEngine.on("message_received",d);let p=await this.negotiationEngine.runFullNegotiation(r,l,c);this.negotiationEngine.off("message_received",d);let h={sessionId:r.id,success:p.success,proposal:p.proposal,participants:l,rounds:p.rounds,totalMessages:p.messageCount,duration:p.duration,failureReason:p.success?void 0:"Negotiation failed"};if(!h.success||!h.proposal)return this.emitEvent({type:"negotiation_failed",reason:h.failureReason??"\u672A\u80FD\u8FBE\u6210\u5171\u8BC6"}),n?.onNegotiation?.({sessionId:h.sessionId,participants:h.participants,status:"failed",rounds:h.rounds}),this.executePipelineMode(e,t,s,h.failureReason??"\u534F\u5546\u5931\u8D25",n);this.emitEvent({type:"consensus_reached",proposal:h.proposal}),n?.onNegotiation?.({sessionId:h.sessionId,participants:h.participants,status:"consensus",rounds:h.rounds});let g;if(p.session)try{g=await this.negotiationSummarizer.summarize(p.session);}catch(C){m.warn("NETWORK","Negotiation summary failed",{error:C instanceof Error?C.message:String(C)});}n?.onThinking?.("\u6B63\u5728\u6784\u5EFA\u6267\u884C\u8BA1\u5212...");let f=this.dagBuilder.createFromProposal(h.proposal);this.emitEvent({type:"dag_created",dag:f});let b=this.dagScheduler.calculateCriticalPath(f);m.debug("NETWORK","DAG scheduled",{dagId:f.id,criticalPathLength:b.criticalPath.length,estimatedDuration:b.totalDuration});let y=this.computeDAGLevels(f),w=[];for(let[C,k]of f.nodes)w.push({id:C,description:k.task?.description||C,agentId:k.assignedAgent||"unassigned",level:k.level,dependencies:k.dependencies||[]});return n?.onDAGCreated?.({id:f.id,nodeCount:f.nodes.size,levelCount:y.length,maxParallelism:Math.max(...y.map(C=>C.length),1),criticalPath:b.criticalPath,estimatedTime:b.totalDuration,nodes:w}),this.interruptedState={prompt:e.prompt,context:e.context,dagId:f.id,selectedAgentIds:l,negotiationRounds:h.rounds,negotiation:h,negotiationSummary:g,handlers:n,interruptedAt:Date.now()},this.executeDagAndFinalize(f,{startTime:s,selectedAgentIds:l,negotiation:h,negotiationRounds:h.rounds,negotiationSummary:g},n)}async executeDagAndFinalize(e,t,s){s?.onThinking?.("\u6B63\u5728\u6267\u884C\u4EFB\u52A1..."),this.emitEvent({type:"execution_started",dagId:e.id});let n=y=>{let w=e.nodes.get(y.nodeId);this.currentExecutingAgentId=y.agentId,this.currentDagId=y.dagId,s?.onNodeStart?.({nodeId:y.nodeId,agentId:y.agentId,description:w?.task?.description||""});},r=y=>{let w=e.nodes.get(y.nodeId);this.currentExecutingAgentId===w?.assignedAgent&&(this.currentExecutingAgentId=null);let C=this.formatNodeOutputPreview(y.result?.output||y.output||"");s?.onNodeComplete?.({nodeId:y.nodeId,agentId:w?.assignedAgent||"",description:w?.task?.description||"",output:C,duration:w?.completedAt&&w?.startedAt?w.completedAt-w.startedAt:0,tokenUsage:y.result?.tokenUsage}),this.updateProgress(e,s);},i=y=>{let w=e.nodes.get(y.nodeId);s?.onNodeFail?.({nodeId:y.nodeId,agentId:w?.assignedAgent||"",description:w?.task?.description||"",error:y.error}),this.updateProgress(e,s);},o=new Map,l=y=>{s?.onAgentText?.(y.agentId,y.text);},c=y=>{let w=y.toolId||`${y.agentId}-tool-${y.nodeId}`;o.set(y.agentId,w),s?.onToolStart?.({agentId:y.agentId,toolName:y.tool,toolId:w,args:y.args,targetPath:y.targetPath,description:y.description});},u=y=>{let w=y.toolId||o.get(y.agentId)||`${y.agentId}-tool-${y.nodeId}`;s?.onToolEnd?.({agentId:y.agentId,toolName:y.tool,toolId:w,success:y.success,output:y.output,outputTruncated:y.outputTruncated,args:y.args,summary:y.summary,duration:y.duration});},d=y=>{s?.onReplan?.({dagId:y.dagId,trigger:y.trigger.type,reason:y.trigger.reason,affectedNodes:y.trigger.failedNodeId?[y.trigger.failedNodeId]:[]});};this.dagExecutor.on("node_started",n),this.dagExecutor.on("node_completed",r),this.dagExecutor.on("node_failed",i),this.dagExecutor.on("node_text",l),this.dagExecutor.on("node_tool_start",c),this.dagExecutor.on("node_tool_end",u),this.replanningEngine.on("replan_started",d);let p;try{p=await this.dagExecutor.execute(e.id,this.abortController?.signal);}finally{this.dagExecutor.off("node_started",n),this.dagExecutor.off("node_completed",r),this.dagExecutor.off("node_failed",i),this.dagExecutor.off("node_text",l),this.dagExecutor.off("node_tool_start",c),this.dagExecutor.off("node_tool_end",u),this.replanningEngine.off("replan_started",d);}this.updateProgress(e,s),this.emitEvent({type:"execution_completed",result:p});let h=e.status;if(h==="paused"||h==="cancelled"||this.aborted){let y=p.errors[p.errors.length-1]?.error||"\u4EFB\u52A1\u5DF2\u6682\u505C";throw this.markInterruptedState(e.id,this.interruptedState?.reason||y),new Error("Network execution paused")}s?.onThinking?.("\u6B63\u5728\u8FDB\u884C\u4E92\u8BC4..."),this.emitEvent({type:"peer_review_started",dagId:e.id});let g=await this.conductPeerReviews(e,p);this.emitEvent({type:"peer_review_completed",summary:g}),s?.onPeerReview?.({reviewers:g.reputationUpdates.map(y=>y.agentId),averageScore:g.averageScore,summary:`${g.reviewCount} \u6B21\u8BC4\u5BA1\uFF0C\u5E73\u5747 ${g.averageScore.toFixed(1)}/5`});let f=await this.updateReputations(e,p,g);this.emitEvent({type:"reputation_updated",updates:f});let b={output:p.finalOutput??"",summary:{mode:"network",agentCount:t.selectedAgentIds.length,agents:t.selectedAgentIds,negotiationRounds:t.negotiationRounds,dagVersion:e.version,totalDuration:Date.now()-t.startTime,totalTokens:p.tokenStats?.total??0,successfulTasks:p.completedNodes,failedTasks:p.failedNodes},dag:e,negotiation:t.negotiation,negotiationSummary:t.negotiationSummary,peerReviews:g};return this.emitEvent({type:"chat_completed",response:b}),s?.onComplete?.(`\u6267\u884C\u5B8C\u6210: ${p.completedNodes}/${e.nodes.size} \u4EFB\u52A1\u6210\u529F`),s?.onText?.(b.output),this.interruptedState=null,b}formatNodeOutputPreview(e){if(!e)return "";let n=e.replace(/```[\s\S]*?```/g,"").replace(/\r\n/g,`
3312
3312
  `).split(`
3313
3313
  `).map(i=>i.trim()).filter(i=>i.length>0).find(i=>!i.startsWith("{")&&!i.startsWith("["));if(!n)return "";let r=n.replace(/\s+/g," ");return r.length>160?`${r.slice(0,157)}...`:r}updateProgress(e,t){let s=0,n=0,r=0,i=0;for(let[,o]of e.nodes)switch(o.status){case "completed":s++;break;case "running":n++;break;case "failed":i++;break;default:r++;}t?.onProgress?.({completed:s,running:n,pending:r,failed:i,total:e.nodes.size});}computeDAGLevels(e){let t=[],s=new Set,n=new Set(e.nodes.keys());for(;n.size>0;){let r=[];for(let i of n)(e.nodes.get(i).dependencies||[]).every(c=>s.has(c))&&r.push(i);if(r.length===0)break;for(let i of r)s.add(i),n.delete(i);t.push(r);}return t}async executeSimpleMode(e,t,s,n){if(this.aborted)throw new Error("Task aborted by user");n?.onThinking?.("\u6B63\u5728\u5206\u914D Agent...");let r=await this.agentMatcher.matchOrCreate({subtask:{id:"simple-task",description:t.description,dependencies:[],estimatedTime:6e4,estimatedTokens:t.estimatedTokens,requiredCapabilities:t.requiredCapabilities},requiredCapabilities:t.requiredCapabilities}),i=r.agent;n?.onNodeStart?.({nodeId:"simple-task",agentId:i.id,description:t.description||e.prompt.slice(0,100)}),n?.onThinking?.(`Agent ${i.id} \u6B63\u5728\u6267\u884C...`);let o=0,l=new Map,c=g=>{n?.onAgentText?.(g.agentId,g.text);},u=g=>{let f=g.toolId||`${g.agentId}-tool-${++o}`;m.debug("NETWORK",`Agent ${g.agentId} tool start: ${g.tool}`),l.set(g.agentId,f),n?.onToolStart?.({agentId:g.agentId,toolName:g.tool,toolId:f,args:g.args,targetPath:g.targetPath,description:g.description});},d=g=>{let f=g.toolId||l.get(g.agentId)||`${g.agentId}-tool-${o}`;m.debug("NETWORK",`Agent ${g.agentId} tool end: ${g.tool}`),n?.onToolEnd?.({agentId:g.agentId,toolName:g.tool,toolId:f,success:g.success,output:g.output,outputTruncated:g.outputTruncated,args:g.args,summary:g.summary,duration:g.duration});};i.on("task_text",c),i.on("task_tool_start",u),i.on("task_tool_end",d),m.debug("NETWORK",`Agent ${i.id} starting executeTask`,{isNewlyCreated:r.isNewlyCreated,score:r.score});let p;try{p=await i.executeTask(e.prompt,void 0,void 0,{abortSignal:this.abortController?.signal});}finally{i.off("task_text",c),i.off("task_tool_start",u),i.off("task_tool_end",d);}m.debug("NETWORK",`Agent ${i.id} completed executeTask`,{outputLength:p.output?.length}),n?.onNodeComplete?.({nodeId:"simple-task",agentId:i.id,description:t.description||e.prompt.slice(0,100),output:this.formatNodeOutputPreview(p.output),duration:Date.now()-s,tokenUsage:p.tokenUsage});let h={output:p.output,summary:{mode:"simple",agentCount:1,agents:[i.id],negotiationRounds:0,dagVersion:0,totalDuration:Date.now()-s,totalTokens:p.tokenUsage?.total??0,successfulTasks:1,failedTasks:0}};return this.emitEvent({type:"chat_completed",response:h}),n?.onComplete?.("\u6267\u884C\u5B8C\u6210 (Simple \u6A21\u5F0F)"),n?.onText?.(h.output),h}async executePipelineMode(e,t,s,n,r){if(this.aborted)throw new Error("Task aborted by user");r?.onThinking?.(`\u964D\u7EA7\u5230 Pipeline \u6A21\u5F0F: ${n}`);let i={id:`pipeline-${Date.now()}`,description:t.description,userRequest:e.prompt,requiredCapabilities:t.requiredCapabilities,optionalCapabilities:t.optionalCapabilities,estimatedComplexity:t.complexity,priority:t.priority,tokenBudget:e.tokenBudget,broadcastedAt:Date.now(),bidDeadline:Date.now()+3e4};r?.onThinking?.("\u6B63\u5728\u751F\u6210\u6267\u884C\u8BA1\u5212...");let o=await this.proposalGenerator.generateProposal(`pipeline-${Date.now()}`,i,[]),l=this.dagBuilder.createFromProposal(o),c=this.dagScheduler.calculateCriticalPath(l),u=this.computeDAGLevels(l),d=[];for(let[_,M]of l.nodes)d.push({id:_,description:M.task?.description||_,agentId:M.assignedAgent||"unassigned",level:M.level,dependencies:M.dependencies||[]});r?.onDAGCreated?.({id:l.id,nodeCount:l.nodes.size,levelCount:u.length,maxParallelism:Math.max(...u.map(_=>_.length),1),criticalPath:c.criticalPath,estimatedTime:c.totalDuration,nodes:d});let p=_=>{let M=l.nodes.get(_.nodeId);r?.onNodeStart?.({nodeId:_.nodeId,agentId:_.agentId,description:M?.task?.description||""});},h=_=>{let M=l.nodes.get(_.nodeId),F=this.formatNodeOutputPreview(_.result?.output||"");r?.onNodeComplete?.({nodeId:_.nodeId,agentId:M?.assignedAgent||"",description:M?.task?.description||"",output:F,duration:M?.completedAt&&M?.startedAt?M.completedAt-M.startedAt:0,tokenUsage:_.result?.tokenUsage}),this.updateProgress(l,r);},g=_=>{let M=l.nodes.get(_.nodeId);r?.onNodeFail?.({nodeId:_.nodeId,agentId:M?.assignedAgent||"",description:M?.task?.description||"",error:_.error}),this.updateProgress(l,r);},f=new Map,b=_=>{r?.onAgentText?.(_.agentId,_.text);},y=_=>{let M=_.toolId||`${_.agentId}-tool-${_.nodeId}`;f.set(_.agentId,M),r?.onToolStart?.({agentId:_.agentId,toolName:_.tool,toolId:M,args:_.args,targetPath:_.targetPath,description:_.description});},w=_=>{let M=_.toolId||f.get(_.agentId)||`${_.agentId}-tool-${_.nodeId}`;r?.onToolEnd?.({agentId:_.agentId,toolName:_.tool,toolId:M,success:_.success,output:_.output,outputTruncated:_.outputTruncated,args:_.args,summary:_.summary,duration:_.duration});};this.dagExecutor.on("node_started",p),this.dagExecutor.on("node_completed",h),this.dagExecutor.on("node_failed",g),this.dagExecutor.on("node_text",b),this.dagExecutor.on("node_tool_start",y),this.dagExecutor.on("node_tool_end",w),r?.onThinking?.("\u6B63\u5728\u6267\u884C\u4EFB\u52A1...");let C=await this.dagExecutor.execute(l.id,this.abortController?.signal);this.dagExecutor.off("node_started",p),this.dagExecutor.off("node_completed",h),this.dagExecutor.off("node_failed",g),this.dagExecutor.off("node_text",b),this.dagExecutor.off("node_tool_start",y),this.dagExecutor.off("node_tool_end",w),this.updateProgress(l,r);let k=new Set;for(let _ of l.nodes.values())_.assignedAgent&&k.add(_.assignedAgent);let T={output:C.finalOutput??"",summary:{mode:"pipeline",fallbackReason:n,agentCount:k.size,agents:Array.from(k),negotiationRounds:0,dagVersion:l.version,totalDuration:Date.now()-s,totalTokens:C.tokenStats?.total??0,successfulTasks:C.completedNodes,failedTasks:C.failedNodes},dag:l};return this.emitEvent({type:"chat_completed",response:T}),r?.onComplete?.(`\u6267\u884C\u5B8C\u6210 (Pipeline \u6A21\u5F0F: ${n})`),r?.onText?.(T.output),T}async analyzeTask(e,t){m.debug("NETWORK",">>> analyzeTask: building prompt");let s=`
3314
3314
  \u5206\u6790\u4EE5\u4E0B\u7528\u6237\u8BF7\u6C42\uFF0C\u63D0\u53D6\u4EFB\u52A1\u4FE1\u606F\uFF1A
@@ -3345,7 +3345,7 @@ ${t}
3345
3345
  ## \u8F93\u51FA\u8981\u6C42
3346
3346
  - \u63D0\u4F9B\u6E05\u6670\u3001\u53EF\u6267\u884C\u7684\u89E3\u51B3\u65B9\u6848
3347
3347
  - \u89E3\u91CA\u5173\u952E\u51B3\u7B56\u7684\u7406\u7531
3348
- - \u6807\u6CE8\u6F5C\u5728\u98CE\u9669\u548C\u6539\u8FDB\u70B9`}subscribeExistingAgents(){for(let e of this.registry.getAll())this.subscribeAgent(e.id);}subscribeAgent(e){if(this.agentSubscriptions.has(e))return;let t=this.registry.getInstance(e);if(!t)return;let s=this.messageBus.subscribeForAgent(e,async n=>{if(n.type!=="task_broadcast")return;let r=n.payload;if(!(Date.now()>r.bidDeadline))try{let i=await t.evaluateTask(r);i.participate&&i.bid&&await this.messageBus.publishBid(i.bid);}catch(i){m.warn("NETWORK","Agent bid failed",{agentId:e,error:i instanceof Error?i.message:String(i)});}});this.agentSubscriptions.set(e,s);}unsubscribeAgent(e){let t=this.agentSubscriptions.get(e);t&&(t(),this.agentSubscriptions.delete(e));}clearAgentSubscriptions(){for(let e of this.agentSubscriptions.values())e();this.agentSubscriptions.clear();}async handleReplanRequired(e){let t=(e.trigger.reason+" "+(e.trigger.error||"")).toLowerCase();if(e.trigger.type==="timeout"||t.includes("timeout")||t.includes("timed out")||t.includes("format")||t.includes("schema")||t.includes("invalid")){let n=e.trigger.error||e.trigger.reason;this.markInterruptedState(e.dagId,n),this.dagExecutor.pause(e.dagId),m.warn("NETWORK","Paused DAG for manual resume due to unstable failure",{dagId:e.dagId,reason:n});return}try{let n=await this.replanningEngine.handleTrigger(e.dagId,e.trigger,{failedNodes:e.failedNodes,completedNodes:e.completedNodes});if(n.success){this.refreshDataFlow(e.dagId);return}let r=n.reason||e.trigger.reason;this.markInterruptedState(e.dagId,r),this.dagExecutor.pause(e.dagId),m.warn("NETWORK","Paused DAG because replan failed",{dagId:e.dagId,reason:r});}catch(n){let r=n instanceof Error?n.message:String(n);this.markInterruptedState(e.dagId,r),this.dagExecutor.pause(e.dagId),m.warn("NETWORK","Replan handling failed, DAG paused",{dagId:e.dagId,error:r});}}refreshDataFlow(e){let t=this.dagBuilder.getDAG(e);t&&this.rgpsDataFlowManager.inferFromDAG(t);}setupEventListeners(){this.registry.on("agent_registered",e=>{this.subscribeAgent(e.agentId);}),this.registry.on("agent_unregistered",e=>{this.unsubscribeAgent(e.agentId);}),this.dagExecutor.on("node_started",e=>{this.emitEvent({type:"node_started",dagId:e.dagId,nodeId:e.nodeId,agentId:e.agentId});}),this.dagExecutor.on("node_completed",e=>{this.emitEvent({type:"node_completed",dagId:e.dagId,nodeId:e.nodeId,output:e.output});}),this.dagExecutor.on("node_failed",e=>{this.emitEvent({type:"node_failed",dagId:e.dagId,nodeId:e.nodeId,error:e.error});}),this.dagExecutor.on("replan_required",e=>{this.handleReplanRequired(e);}),this.replanningEngine.on("replan_started",e=>{this.emitEvent({type:"replan_triggered",dagId:e.dagId,reason:e.trigger.reason});}),this.replanningEngine.on("replan_completed",e=>{this.emitEvent({type:"replan_completed",dagId:e.dagId,newVersion:e.newVersion}),this.refreshDataFlow(e.dagId);}),this.biddingEngine.on("bid_received",e=>{this.emitEvent({type:"bid_received",bid:e});}),this.progressiveManager.on("dag_expanded",e=>{this.refreshDataFlow(e.dagId);}),this.progressiveManager.on("user_requirement_inserted",e=>{this.refreshDataFlow(e.dagId);});}emitEvent(e){this.emit(e.type,e),this.emit("network_event",e);}registerAgent(e){return this.registry.register(e)}unregisterAgent(e){return this.registry.unregister(e)}getAgents(){return this.registry.getAll()}getActiveAgents(){return this.registry.getActive()}getAgentFactory(){return this.agentFactory}getRegistry(){return this.registry}getMessageBus(){return this.messageBus}getModelCapabilityRegistry(){return this.modelCapabilityRegistry}getDAGScheduler(){return this.dagScheduler}isStarted(){return this.started}async resume(e){if(!this.interruptedState)throw new Error("\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4E2D\u65AD\u4EFB\u52A1");let t=this.interruptedState,s=this.dagBuilder.getDAG(t.dagId);if(!s)throw this.interruptedState=null,new Error("\u4E2D\u65AD\u4EFB\u52A1\u5BF9\u5E94\u7684 DAG \u5DF2\u4E0D\u5B58\u5728");this.started||this.start(),this.aborted=false,this.abortController=new AbortController,this.executing=true,this.currentExecutingAgentId=null,this.currentDagId=s.id,this.currentPrompt=t.prompt,this.pendingUserMessages=[];let n=e||t.handlers;this.interruptedState={...t,handlers:n,interruptedAt:Date.now()};let r=this.computeDAGLevels(s),i=[];for(let[o,l]of s.nodes)i.push({id:o,description:l.task?.description||o,agentId:l.assignedAgent||"unassigned",level:l.level,dependencies:l.dependencies||[]});n?.onThinking?.("\u6062\u590D\u6267\u884C\u4E2D..."),n?.onDAGCreated?.({id:s.id,nodeCount:s.nodes.size,levelCount:r.length,maxParallelism:Math.max(...r.map(o=>o.length),1),criticalPath:s.analysis.criticalPath,estimatedTime:s.analysis.estimatedTotalTime,nodes:i}),this.updateProgress(s,n);try{return await this.executeDagAndFinalize(s,{startTime:Date.now(),selectedAgentIds:t.selectedAgentIds,negotiation:t.negotiation,negotiationRounds:t.negotiationRounds,negotiationSummary:t.negotiationSummary},n)}finally{this.executing=false,this.currentExecutingAgentId=null,this.currentDagId=null,this.currentPrompt=null;}}getModeName(){return "network"}abort(){m.info("NETWORK","Aborting network runtime"),this.aborted=true,this.currentDagId&&(this.markInterruptedState(this.currentDagId,"Task aborted by user"),this.dagExecutor.pause(this.currentDagId)),this.abortController&&(this.abortController.abort(),this.abortController=null),m.info("NETWORK","Aborted (state preserved for resume)",{dagId:this.currentDagId});}isAborted(){return this.aborted}};W();W();W();W();var Wo=class{config;constructor(e){this.config=e;}create(e){switch(m.info("MODE_FACTORY",`Creating runtime for mode: ${e}`),e){case "single":return this.createSingleAgent();case "assistant":return this.createAssistantAgent();case "cooperate":return this.createCooperateAgent();case "network":return this.createNetworkAgent();default:return m.warn("MODE_FACTORY",`Unknown mode: ${e}, falling back to single`),this.createSingleAgent()}}createSingleAgent(){return new wn({services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt})}createAssistantAgent(){return new xn({services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt})}createCooperateAgent(){return new ps({services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt,ccbReviewMode:this.config.ccbReviewMode,workerModels:this.config.workerModels})}createNetworkAgent(){let e=this.config.orchestrator?{orchestrator:this.config.orchestrator,tools:this.config.tools,permissionManager:this.config.permissionManager,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,maxIterations:30}:void 0;return new Rn({llmCall:this.createLLMCall(),executionCapability:e,autoCreateDefaultAgents:true})}createLLMCall(){let{orchestrator:e}=this.config;return async(t,s)=>{if(!e)throw new Error("Orchestrator not available for LLM call");let n="",r=`network-llm-${Date.now()}`;return await e.runSession({sessionId:r,prompt:s,buildHostConfig:(i,o)=>({sessionId:r,configKey:"network_llm_call",provider:i,llmConfig:o,workspacePath:this.config.workDir,workDir:this.config.workDir,instructions:t,systemPrompt:t,agentName:"NetworkLLM",agentDescription:"Network mode LLM caller",permissionManager:this.config.permissionManager,tools:[],memory:this.config.memory,agentConfig:{maxIterations:1,temperature:.3},sessionEnabled:false,disableSystemPrompt:true}),onRuntimeEvent:i=>{i.type==="text"&&(n+=i.delta);}}),n}}static getDefaultMode(){return "single"}static isValidMode(e){return ["single","assistant","cooperate","network"].includes(e)}static getAvailableModes(){return ["single","assistant","cooperate","network"]}static getModeDescription(e){switch(e){case "single":return "\u5355\u673A\u6A21\u5F0F - \u65E5\u5E38\u5F00\u53D1\uFF0C\u5FEB\u901F\u8FED\u4EE3";case "assistant":return "\u52A9\u7406\u6A21\u5F0F - AI \u52A9\u7406\uFF0C\u8F7B\u91CF supervisor + spawn";case "cooperate":return "\u534F\u540C\u6A21\u5F0F - \u9759\u6001 DAG + CCB \u8BC4\u5BA1\u6D41\u7A0B";case "network":return "\u81EA\u7EC4\u7F51\u6A21\u5F0F - Agent \u81EA\u4E3B\u7EC4\u7F51\uFF0C\u52A8\u6001\u534F\u5546 (\u5F00\u53D1\u4E2D)";default:return ""}}};W();var nk=[".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"],Jm={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:nk};var qo=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={...Jm,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=Km();}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=Km(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=Vm.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(`
3348
+ - \u6807\u6CE8\u6F5C\u5728\u98CE\u9669\u548C\u6539\u8FDB\u70B9`}subscribeExistingAgents(){for(let e of this.registry.getAll())this.subscribeAgent(e.id);}subscribeAgent(e){if(this.agentSubscriptions.has(e))return;let t=this.registry.getInstance(e);if(!t)return;let s=this.messageBus.subscribeForAgent(e,async n=>{if(n.type!=="task_broadcast")return;let r=n.payload;if(!(Date.now()>r.bidDeadline))try{let i=await t.evaluateTask(r);i.participate&&i.bid&&await this.messageBus.publishBid(i.bid);}catch(i){m.warn("NETWORK","Agent bid failed",{agentId:e,error:i instanceof Error?i.message:String(i)});}});this.agentSubscriptions.set(e,s);}unsubscribeAgent(e){let t=this.agentSubscriptions.get(e);t&&(t(),this.agentSubscriptions.delete(e));}clearAgentSubscriptions(){for(let e of this.agentSubscriptions.values())e();this.agentSubscriptions.clear();}async handleReplanRequired(e){let t=(e.trigger.reason+" "+(e.trigger.error||"")).toLowerCase();if(e.trigger.type==="timeout"||t.includes("timeout")||t.includes("timed out")||t.includes("format")||t.includes("schema")||t.includes("invalid")){let n=e.trigger.error||e.trigger.reason;this.markInterruptedState(e.dagId,n),this.dagExecutor.pause(e.dagId),m.warn("NETWORK","Paused DAG for manual resume due to unstable failure",{dagId:e.dagId,reason:n});return}try{let n=await this.replanningEngine.handleTrigger(e.dagId,e.trigger,{failedNodes:e.failedNodes,completedNodes:e.completedNodes});if(n.success){this.refreshDataFlow(e.dagId);return}let r=n.reason||e.trigger.reason;this.markInterruptedState(e.dagId,r),this.dagExecutor.pause(e.dagId),m.warn("NETWORK","Paused DAG because replan failed",{dagId:e.dagId,reason:r});}catch(n){let r=n instanceof Error?n.message:String(n);this.markInterruptedState(e.dagId,r),this.dagExecutor.pause(e.dagId),m.warn("NETWORK","Replan handling failed, DAG paused",{dagId:e.dagId,error:r});}}refreshDataFlow(e){let t=this.dagBuilder.getDAG(e);t&&this.rgpsDataFlowManager.inferFromDAG(t);}setupEventListeners(){this.registry.on("agent_registered",e=>{this.subscribeAgent(e.agentId);}),this.registry.on("agent_unregistered",e=>{this.unsubscribeAgent(e.agentId);}),this.dagExecutor.on("node_started",e=>{this.emitEvent({type:"node_started",dagId:e.dagId,nodeId:e.nodeId,agentId:e.agentId});}),this.dagExecutor.on("node_completed",e=>{this.emitEvent({type:"node_completed",dagId:e.dagId,nodeId:e.nodeId,output:e.output});}),this.dagExecutor.on("node_failed",e=>{this.emitEvent({type:"node_failed",dagId:e.dagId,nodeId:e.nodeId,error:e.error});}),this.dagExecutor.on("replan_required",e=>{this.handleReplanRequired(e);}),this.replanningEngine.on("replan_started",e=>{this.emitEvent({type:"replan_triggered",dagId:e.dagId,reason:e.trigger.reason});}),this.replanningEngine.on("replan_completed",e=>{this.emitEvent({type:"replan_completed",dagId:e.dagId,newVersion:e.newVersion}),this.refreshDataFlow(e.dagId);}),this.biddingEngine.on("bid_received",e=>{this.emitEvent({type:"bid_received",bid:e});}),this.progressiveManager.on("dag_expanded",e=>{this.refreshDataFlow(e.dagId);}),this.progressiveManager.on("user_requirement_inserted",e=>{this.refreshDataFlow(e.dagId);});}emitEvent(e){this.emit(e.type,e),this.emit("network_event",e);}registerAgent(e){return this.registry.register(e)}unregisterAgent(e){return this.registry.unregister(e)}getAgents(){return this.registry.getAll()}getActiveAgents(){return this.registry.getActive()}getAgentFactory(){return this.agentFactory}getRegistry(){return this.registry}getMessageBus(){return this.messageBus}getModelCapabilityRegistry(){return this.modelCapabilityRegistry}getDAGScheduler(){return this.dagScheduler}isStarted(){return this.started}async resume(e){if(!this.interruptedState)throw new Error("\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4E2D\u65AD\u4EFB\u52A1");let t=this.interruptedState,s=this.dagBuilder.getDAG(t.dagId);if(!s)throw this.interruptedState=null,new Error("\u4E2D\u65AD\u4EFB\u52A1\u5BF9\u5E94\u7684 DAG \u5DF2\u4E0D\u5B58\u5728");this.started||this.start(),this.aborted=false,this.abortController=new AbortController,this.executing=true,this.currentExecutingAgentId=null,this.currentDagId=s.id,this.currentPrompt=t.prompt,this.pendingUserMessages=[];let n=e||t.handlers;this.interruptedState={...t,handlers:n,interruptedAt:Date.now()};let r=this.computeDAGLevels(s),i=[];for(let[o,l]of s.nodes)i.push({id:o,description:l.task?.description||o,agentId:l.assignedAgent||"unassigned",level:l.level,dependencies:l.dependencies||[]});n?.onThinking?.("\u6062\u590D\u6267\u884C\u4E2D..."),n?.onDAGCreated?.({id:s.id,nodeCount:s.nodes.size,levelCount:r.length,maxParallelism:Math.max(...r.map(o=>o.length),1),criticalPath:s.analysis.criticalPath,estimatedTime:s.analysis.estimatedTotalTime,nodes:i}),this.updateProgress(s,n);try{return await this.executeDagAndFinalize(s,{startTime:Date.now(),selectedAgentIds:t.selectedAgentIds,negotiation:t.negotiation,negotiationRounds:t.negotiationRounds,negotiationSummary:t.negotiationSummary},n)}finally{this.executing=false,this.currentExecutingAgentId=null,this.currentDagId=null,this.currentPrompt=null;}}getModeName(){return "network"}abort(){m.info("NETWORK","Aborting network runtime"),this.aborted=true,this.currentDagId&&(this.markInterruptedState(this.currentDagId,"Task aborted by user"),this.dagExecutor.pause(this.currentDagId)),this.abortController&&(this.abortController.abort(),this.abortController=null),m.info("NETWORK","Aborted (state preserved for resume)",{dagId:this.currentDagId});}isAborted(){return this.aborted}};W();W();W();W();var Wo=class{config;constructor(e){this.config=e;}create(e){switch(m.info("MODE_FACTORY",`Creating runtime for mode: ${e}`),e){case "single":return this.createSingleAgent();case "assistant":return this.createAssistantAgent();case "cooperate":return this.createCooperateAgent();case "network":return this.createNetworkAgent();default:return m.warn("MODE_FACTORY",`Unknown mode: ${e}, falling back to single`),this.createSingleAgent()}}createSingleAgent(){return new wn({services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt})}createAssistantAgent(){return new xn({services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt})}createCooperateAgent(){return new ps({services:this.config.services,permissionManager:this.config.permissionManager,tools:this.config.tools,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,systemPrompt:this.config.systemPrompt,ccbReviewMode:this.config.ccbReviewMode,workerModels:this.config.workerModels})}createNetworkAgent(){let e=this.config.orchestrator?{orchestrator:this.config.orchestrator,tools:this.config.tools,permissionManager:this.config.permissionManager,memory:this.config.memory,workDir:this.config.workDir,providerId:this.config.providerId,modelName:this.config.modelName,resolveProvider:this.config.resolveProvider,maxIterations:30}:void 0;return new Rn({llmCall:this.createLLMCall(),executionCapability:e,autoCreateDefaultAgents:true})}createLLMCall(){let{orchestrator:e}=this.config;return async(t,s)=>{if(!e)throw new Error("Orchestrator not available for LLM call");let n="",r=`network-llm-${Date.now()}`;return await e.runSession({sessionId:r,prompt:s,buildHostConfig:(i,o)=>({sessionId:r,configKey:"network_llm_call",provider:i,llmConfig:o,workspacePath:this.config.workDir,workDir:this.config.workDir,instructions:t,systemPrompt:t,agentName:"NetworkLLM",agentDescription:"Network mode LLM caller",permissionManager:this.config.permissionManager,tools:[],memory:this.config.memory,agentConfig:{maxIterations:1,temperature:.3},sessionEnabled:false,disableSystemPrompt:true}),onRuntimeEvent:i=>{i.type==="text"&&(n+=i.delta);}}),n}}static getDefaultMode(){return "single"}static isValidMode(e){return ["single","assistant","cooperate","network"].includes(e)}static getAvailableModes(){return ["single","assistant","cooperate","network"]}static getModeDescription(e){switch(e){case "single":return "\u5355\u673A\u6A21\u5F0F - \u65E5\u5E38\u5F00\u53D1\uFF0C\u5FEB\u901F\u8FED\u4EE3";case "assistant":return "\u52A9\u7406\u6A21\u5F0F - AI \u52A9\u7406\uFF0C\u8F7B\u91CF supervisor + spawn";case "cooperate":return "\u534F\u540C\u6A21\u5F0F - \u9759\u6001 DAG + CCB \u8BC4\u5BA1\u6D41\u7A0B";case "network":return "\u81EA\u7EC4\u7F51\u6A21\u5F0F - Agent \u81EA\u4E3B\u7EC4\u7F51\uFF0C\u52A8\u6001\u534F\u5546 (\u5F00\u53D1\u4E2D)";default:return ""}}};W();var rk=[".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"],Jm={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:rk};var qo=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={...Jm,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=Km();}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=Km(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=Vm.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(`
3349
3349
  `).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?`
3350
3350
 
3351
3351
  Session: ${this.currentSessionId}
@@ -3358,7 +3358,7 @@ Stats: +${t.created} ~${t.modified} -${t.deleted} d${t.directories}${s}`}parseCo
3358
3358
  .cdundo/
3359
3359
  `:`# Neox checkpoint directory
3360
3360
  .cdundo/
3361
- `;await ce.writeFile(e,s),m.debug("CHECKPOINT","Added .cdundo to .gitignore");}}catch(t){m.error("CHECKPOINT","Failed to update .gitignore",{error:t});}}async cleanupOldCheckpoints(){try{let e=await this.getCheckpoints(this.config.maxCheckpoints+10);e.length>this.config.maxCheckpoints&&(m.debug("CHECKPOINT",`Cleaning up old checkpoints (${e.length} > ${this.config.maxCheckpoints})`),await this.compressRepository());}catch(e){m.error("CHECKPOINT","Failed to cleanup checkpoints",{error:e});}}async compressRepository(){if(!this.initialized)return {success:false};try{let e=await this.getRepositorySize();m.debug("CHECKPOINT","Compressing repository..."),await this.git.raw(["reflog","expire","--expire=now","--all"]),await this.git.raw(["gc","--aggressive","--prune=now"]),await this.git.raw(["repack","-a","-d","--depth=250","--window=250"]);let t=await this.getRepositorySize(),s=e-t;return m.debug("CHECKPOINT",`Repository compressed: ${this.formatFileSize(e)} \u2192 ${this.formatFileSize(t)} (saved ${this.formatFileSize(s)})`),{success:!0,savedBytes:s}}catch(e){return m.error("CHECKPOINT","Failed to compress repository",{error:e}),{success:false}}}async getRepositorySize(){let e=0,t=async s=>{try{let n=await ce.readdir(s,{withFileTypes:!0});for(let r of n){let i=te.join(s,r.name);if(r.isDirectory())await t(i);else if(r.isFile()){let o=await ce.stat(i);e+=o.size;}}}catch{}};return await t(this.shadowGitDir),e}async getStorageStats(){let e=await this.getRepositorySize(),t=0,s=async r=>{try{let i=await ce.readdir(r,{withFileTypes:!0});for(let o of i){let l=te.join(r,o.name);if(o.isDirectory()&&o.name!==".git")await s(l);else if(o.isFile()){let c=await ce.stat(l);t+=c.size;}}}catch{}};await s(this.shadowDir);let n=await this.getCheckpoints(1e3);return {repositorySize:e,shadowDirSize:t,checkpointCount:n.length,oldestCheckpoint:n.length>0?{id:n[n.length-1].id,timestamp:n[n.length-1].timestamp}:void 0,newestCheckpoint:n.length>0?{id:n[0].id,timestamp:n[0].timestamp}:void 0}}async cleanStaleLocks(){let e=te.join(this.shadowGitDir,"index.lock");try{if(Me.existsSync(e)){let s=await ce.stat(e);Date.now()-s.mtimeMs>1e4&&(await ce.unlink(e),m.debug("CHECKPOINT","Cleaned stale lock file"));}}catch{}}async withGitLock(e){let t=this.gitOperationLock,s=()=>{};this.gitOperationLock=new Promise(n=>{s=n;});try{await t;let n;for(let r=1;r<=this.GIT_RETRY_ATTEMPTS;r++)try{return r>1&&(await this.cleanStaleLocks(),await new Promise(o=>setTimeout(o,this.GIT_RETRY_DELAY_MS))),await e()}catch(i){if(n=i,!(i.message&&(i.message.includes("index.lock")||i.message.includes("File exists")))||r===this.GIT_RETRY_ATTEMPTS)throw i;m.warn("CHECKPOINT",`Git operation failed (attempt ${r}/${this.GIT_RETRY_ATTEMPTS}), retrying...`);}throw n}finally{s();}}async destroy(){await this.stopWatching(),this.initialized=false,this.changeCallbacks.clear(),m.debug("CHECKPOINT","Instance destroyed");}};var Mr=class a{static instance=null;instances=new Map;config;constructor(e={}){this.config=e;}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}async getCheckpoint(e){let t=te.normalize(e);if(!this.instances.has(t)){let s=new qo(this.config);await s.init(t),this.instances.set(t,s);}return this.instances.get(t)}async startWatching(e,t,s=0){return (await this.getCheckpoint(e)).startWatching(t,s)}getBeforeCheckpointId(e){let t=te.normalize(e);return this.instances.get(t)?.getBeforeCheckpointId()??null}async stopWatching(e){let t=te.normalize(e),s=this.instances.get(t);s&&await s.stopWatching();}async createCheckpoint(e,t){return (await this.getCheckpoint(e)).createCheckpoint(t)}async rollbackTo(e,t){return (await this.getCheckpoint(e)).rollbackTo(t)}async rollbackSingleFile(e,t){return (await this.getCheckpoint(e)).rollbackSingleFile(t)}async reapplySingleFile(e,t){return (await this.getCheckpoint(e)).reapplySingleFile(t)}async getCheckpoints(e,t,s){return (await this.getCheckpoint(e)).getCheckpoints(t,s)}async getDiff(e,t,s){return (await this.getCheckpoint(e)).getDiff(t,s)}async getChangeBuffer(e){return (await this.getCheckpoint(e)).getChangeBuffer()}async getCurrentStats(e){return (await this.getCheckpoint(e)).getCurrentStats()}async onFileChange(e,t){return (await this.getCheckpoint(e)).onFileChange(t)}isWatching(e){let t=te.normalize(e);return this.instances.get(t)?.isActive()??false}async cleanup(e){let t=te.normalize(e),s=this.instances.get(t);s&&(await s.destroy(),this.instances.delete(t));let n=te.join(t,".cdundo");try{await ce.rm(n,{recursive:!0,force:!0}),console.log("[CheckpointManager] Cleaned up:",n);}catch(r){console.error("[CheckpointManager] Failed to cleanup:",r);}}async destroyAll(){for(let[e,t]of this.instances)await t.destroy();this.instances.clear(),console.log("[CheckpointManager] All instances destroyed");}getActiveWorkspaces(){return Array.from(this.instances.keys()).filter(e=>this.instances.get(e)?.isActive())}getStats(){return {totalInstances:this.instances.size,activeInstances:this.getActiveWorkspaces().length,workspaces:Array.from(this.instances.keys())}}};Mr.getInstance();var zo=class{checkpointManager;workspacePath=null;enabled=true;sessionMessageCounts=new Map;constructor(e){this.checkpointManager=e??Mr.getInstance();}setWorkspace(e){this.workspacePath=e;}setEnabled(e){this.enabled=e;}isEnabled(){return this.enabled}async startMessage(e){if(!this.enabled||!this.workspacePath)return null;let t=this.sessionMessageCounts.get(e)||0;return this.checkpointManager.startWatching(this.workspacePath,e,t)}async finishMessage(e,t){if(!this.enabled||!this.workspacePath)return null;let s=await this.createCheckpoint(e,t);return await this.checkpointManager.stopWatching(this.workspacePath),s}async stopWatching(){this.workspacePath&&await this.checkpointManager.stopWatching(this.workspacePath);}async createCheckpoint(e,t){if(!this.enabled||!this.workspacePath)return null;let s=this.sessionMessageCounts.get(e)||0,n=t||`Message #${s+1}`,r=await this.checkpointManager.createCheckpoint(this.workspacePath,n);return this.sessionMessageCounts.set(e,s+1),r}async rollbackToCheckpoint(e){return this.workspacePath?this.checkpointManager.rollbackTo(this.workspacePath,e):{success:false,restored:[],errors:["No workspace set"]}}async rollbackSingleFile(e){return this.workspacePath?this.checkpointManager.rollbackSingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async reapplySingleFile(e){return this.workspacePath?this.checkpointManager.reapplySingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async getCheckpoints(e,t){return this.workspacePath?this.checkpointManager.getCheckpoints(this.workspacePath,e,t):[]}async getCurrentStats(){return this.workspacePath?this.checkpointManager.getCurrentStats(this.workspacePath):null}async getChangeBuffer(){return this.workspacePath?this.checkpointManager.getChangeBuffer(this.workspacePath):[]}async cleanup(){this.workspacePath&&await this.checkpointManager.cleanup(this.workspacePath);}};function rk(){throw new Error("Approval prompt is not configured");}async function Qm(a){let{toolName:e,args:t,reason:s,allowRemember:n}=a,r=rk(),i=Object.keys(t).length>0?` (${Object.keys(t).slice(0,2).join(", ")}${Object.keys(t).length>2?"...":""})`:"",o=`Allow tool ${e}${i}?`,l=s?`Warning: ${s}`:void 0,c=[{label:"Allow Once",value:"allow_once",description:"Allow this tool call only this time"}];switch(n&&c.push({label:"Always Allow",value:"always_allow",description:`Don't ask again for "${e}"`}),c.push({label:"Deny",value:"deny",description:"Reject this tool call"}),await r(o,c,"allow_once",l)){case "allow_once":return {approved:true,remember:false};case "always_allow":return {approved:true,remember:true};case "deny":return {approved:false,remember:false};default:return {approved:false,remember:false}}}function Zm(a="auto"){let e=a==="dangerous",t=a==="manual",s=new ls({approvalHandler:e?void 0:Qm,defaultPermission:e?"allow":t?"ask":"allow",memoryExpirationMs:1440*60*1e3});return e||_l(s),s}W();var ok=te__default.join(vs,"workspaces"),ak=200,lk=20,ck=50,uk=40,dk=4e3,$c=8,pk=240,mk=8,gk=256*1024,Fc=6,Pr=240,eg=512*1024,hk=1500,fk=15e3,yk=6,bk=30,vk="claude-haiku";function wk(a){return a.toLowerCase().replace(/[^a-z0-9-_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,24)||"workspace"}function Ck(a){let e=te__default.resolve(a),t=wk(te__default.basename(e)),s=Yt.createHash("sha1").update(e).digest("hex").slice(0,12);return `${t}-${s}`}function kk(a){return new Date(a).toISOString().slice(0,10)}function Dr(a){let e=new Date(a),t=s=>String(s).padStart(2,"0");return [e.getFullYear(),t(e.getMonth()+1),t(e.getDate())].join("-")+` ${t(e.getHours())}:${t(e.getMinutes())}`}function ot(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var Lr=class{options;workspacePath=null;workspaceId=null;workspaceName=null;eventsDir=null;memoriesDir=null;memoryPaths=null;graphPaths=null;indexPath=null;summaryPath=null;sessionSummaryPath=null;metaPath=null;seq=0;currentDate=null;currentFile=null;currentFileBytes=0;queue=[];sessionSummaryQueue=[];memoryQueue=[];graphNodeQueue=[];graphEdgeQueue=[];summarizerOverrides;summarizerQueue=[];summarizerTimer=null;summarizerRunning=false;summarizerLastRun=0;summarizerProvider=null;summarizerProviderModel=null;summaryItems=[];summaryDirty=false;runAggregates=new Map;flushTimer=null;isFlushing=false;flushPending=false;ready=false;initPromise=null;createdAt=Date.now();constructor(e={}){this.options={flushIntervalMs:e.flushIntervalMs??ak,batchSize:e.batchSize??lk,indexStride:e.indexStride??ck,summaryWindow:e.summaryWindow??uk,maxSummaryChars:e.maxSummaryChars??dk,source:e.source,agentName:e.agentName},this.summarizerOverrides=e.summarizer,e.workspacePath&&this.setWorkspace(e.workspacePath);}async setWorkspace(e){let t=te__default.resolve(e);if(this.workspacePath===t)return;await this.flush(),this.workspacePath=t,this.workspaceName=te__default.basename(t),this.workspaceId=Ck(t);let s=te__default.join(ok,this.workspaceId);this.eventsDir=te__default.join(s,"events"),this.memoriesDir=te__default.join(s,"memories"),this.memoryPaths={progress:te__default.join(this.memoriesDir,"progress.jsonl"),standard:te__default.join(this.memoriesDir,"standards.jsonl"),lesson:te__default.join(this.memoriesDir,"lessons.jsonl"),pinned:te__default.join(this.memoriesDir,"pinned.jsonl")},this.graphPaths={nodes:te__default.join(this.memoriesDir,"graph_nodes.jsonl"),edges:te__default.join(this.memoriesDir,"graph_edges.jsonl")},this.indexPath=te__default.join(this.eventsDir,"index.jsonl"),this.summaryPath=te__default.join(this.eventsDir,"recent_summary.json"),this.sessionSummaryPath=this.memoriesDir?te__default.join(this.memoriesDir,"session_summary.jsonl"):null,this.metaPath=te__default.join(this.eventsDir,"meta.json"),this.currentDate=null,this.currentFile=null,this.currentFileBytes=0,this.sessionSummaryQueue=[],this.memoryQueue=[],this.graphNodeQueue=[],this.graphEdgeQueue=[],this.summarizerQueue=[],this.summarizerProvider=null,this.summarizerProviderModel=null,this.runAggregates.clear(),this.ready=false,this.initPromise=this.initializeWorkspace(),await this.initPromise;}formatFilePath(e){if(!this.workspacePath)return e;let t=te__default.relative(this.workspacePath,e);return !t||t.startsWith("..")?e:t}record(e){if(!this.workspacePath||!this.workspaceId)return;let t={schemaVersion:1,id:Yt.randomUUID(),seq:++this.seq,ts:e.ts??Date.now(),workspaceId:this.workspaceId,workspacePath:this.workspacePath,type:e.type,sessionId:e.sessionId,runId:e.runId,actor:e.actor,summary:e.summary,reason:e.reason,files:e.files,data:e.data};this.queue.push(t),this.updateSummary(t),this.updateRunAggregate(t),this.maybeQueueSessionSummary(t),this.queueMemoryEntries(this.extractMemoryEntries(t),"event"),this.queueGraphEntries(this.extractGraphEntries(t));let s=t.type==="run_result"||t.type==="run_error";(this.queue.length>=this.options.batchSize||s)&&this.flush();}createRunId(){return Yt.randomUUID()}async getContextSummary(e){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let t=e?.language??"zh",s=e?.maxItems??this.options.summaryWindow,n=e?.maxSessionItems??$c,r=e?.maxMemoryItems??Fc,i=e?.maxChars??this.options.maxSummaryChars,o=e?.query?.trim(),l=t==="zh"?{memoryHeader:"## \u9879\u76EE\u8BB0\u5FC6\uFF08\u81EA\u52A8\uFF09",pinned:"### \u56FA\u5B9A",progress:"### \u8FDB\u5EA6",standard:"### \u89C4\u8303",lesson:"### \u6559\u8BAD",sessionHeader:"## \u4F1A\u8BDD\u6458\u8981",activityHeader:"## \u6700\u8FD1\u5DE5\u4F5C\u6458\u8981"}:{memoryHeader:"## Project Memory (Auto)",pinned:"### Pinned",progress:"### Progress",standard:"### Standards",lesson:"### Lessons",sessionHeader:"## Session Summary",activityHeader:"## Recent Workspace Activity"},c=null;if(o){let I=this.tokenizeQuery(o);c={tokens:I,graphMatches:await this.getGraphRunMatches(I)};}let u=o&&c?await this.getRelevantSessionSummaries(o,n,c):await this.getRecentSessionSummaries(n),d=o&&c?await this.getRelevantMemoryItems(o,r,c):{pinned:await this.getRecentMemoryItems("pinned",r),progress:await this.getRecentMemoryItems("progress",r),standard:await this.getRecentMemoryItems("standard",r),lesson:await this.getRecentMemoryItems("lesson",r)},p=d.pinned,h=d.progress,g=d.standard,f=d.lesson,b=this.summaryItems.slice(-s),y=I=>I.map(A=>`- [${Dr(A.ts)}] ${A.summary}`),w=y(u),C=y(p),k=y(h),T=y(g),_=y(f),M=y(b),F=[{key:"pinned",title:l.pinned,lines:C},{key:"progress",title:l.progress,lines:k},{key:"standard",title:l.standard,lines:T},{key:"lesson",title:l.lesson,lines:_}],x={key:"activity",title:l.activityHeader,lines:M},R={key:"session",title:l.sessionHeader,lines:w};if(F.every(I=>I.lines.length===0)&&w.length===0&&M.length===0)return null;let j=()=>{let I=[],A=F.filter(O=>O.lines.length>0).map(O=>`${O.title}
3361
+ `;await ce.writeFile(e,s),m.debug("CHECKPOINT","Added .cdundo to .gitignore");}}catch(t){m.error("CHECKPOINT","Failed to update .gitignore",{error:t});}}async cleanupOldCheckpoints(){try{let e=await this.getCheckpoints(this.config.maxCheckpoints+10);e.length>this.config.maxCheckpoints&&(m.debug("CHECKPOINT",`Cleaning up old checkpoints (${e.length} > ${this.config.maxCheckpoints})`),await this.compressRepository());}catch(e){m.error("CHECKPOINT","Failed to cleanup checkpoints",{error:e});}}async compressRepository(){if(!this.initialized)return {success:false};try{let e=await this.getRepositorySize();m.debug("CHECKPOINT","Compressing repository..."),await this.git.raw(["reflog","expire","--expire=now","--all"]),await this.git.raw(["gc","--aggressive","--prune=now"]),await this.git.raw(["repack","-a","-d","--depth=250","--window=250"]);let t=await this.getRepositorySize(),s=e-t;return m.debug("CHECKPOINT",`Repository compressed: ${this.formatFileSize(e)} \u2192 ${this.formatFileSize(t)} (saved ${this.formatFileSize(s)})`),{success:!0,savedBytes:s}}catch(e){return m.error("CHECKPOINT","Failed to compress repository",{error:e}),{success:false}}}async getRepositorySize(){let e=0,t=async s=>{try{let n=await ce.readdir(s,{withFileTypes:!0});for(let r of n){let i=te.join(s,r.name);if(r.isDirectory())await t(i);else if(r.isFile()){let o=await ce.stat(i);e+=o.size;}}}catch{}};return await t(this.shadowGitDir),e}async getStorageStats(){let e=await this.getRepositorySize(),t=0,s=async r=>{try{let i=await ce.readdir(r,{withFileTypes:!0});for(let o of i){let l=te.join(r,o.name);if(o.isDirectory()&&o.name!==".git")await s(l);else if(o.isFile()){let c=await ce.stat(l);t+=c.size;}}}catch{}};await s(this.shadowDir);let n=await this.getCheckpoints(1e3);return {repositorySize:e,shadowDirSize:t,checkpointCount:n.length,oldestCheckpoint:n.length>0?{id:n[n.length-1].id,timestamp:n[n.length-1].timestamp}:void 0,newestCheckpoint:n.length>0?{id:n[0].id,timestamp:n[0].timestamp}:void 0}}async cleanStaleLocks(){let e=te.join(this.shadowGitDir,"index.lock");try{if(Me.existsSync(e)){let s=await ce.stat(e);Date.now()-s.mtimeMs>1e4&&(await ce.unlink(e),m.debug("CHECKPOINT","Cleaned stale lock file"));}}catch{}}async withGitLock(e){let t=this.gitOperationLock,s=()=>{};this.gitOperationLock=new Promise(n=>{s=n;});try{await t;let n;for(let r=1;r<=this.GIT_RETRY_ATTEMPTS;r++)try{return r>1&&(await this.cleanStaleLocks(),await new Promise(o=>setTimeout(o,this.GIT_RETRY_DELAY_MS))),await e()}catch(i){if(n=i,!(i.message&&(i.message.includes("index.lock")||i.message.includes("File exists")))||r===this.GIT_RETRY_ATTEMPTS)throw i;m.warn("CHECKPOINT",`Git operation failed (attempt ${r}/${this.GIT_RETRY_ATTEMPTS}), retrying...`);}throw n}finally{s();}}async destroy(){await this.stopWatching(),this.initialized=false,this.changeCallbacks.clear(),m.debug("CHECKPOINT","Instance destroyed");}};var Mr=class a{static instance=null;instances=new Map;config;constructor(e={}){this.config=e;}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}async getCheckpoint(e){let t=te.normalize(e);if(!this.instances.has(t)){let s=new qo(this.config);await s.init(t),this.instances.set(t,s);}return this.instances.get(t)}async startWatching(e,t,s=0){return (await this.getCheckpoint(e)).startWatching(t,s)}getBeforeCheckpointId(e){let t=te.normalize(e);return this.instances.get(t)?.getBeforeCheckpointId()??null}async stopWatching(e){let t=te.normalize(e),s=this.instances.get(t);s&&await s.stopWatching();}async createCheckpoint(e,t){return (await this.getCheckpoint(e)).createCheckpoint(t)}async rollbackTo(e,t){return (await this.getCheckpoint(e)).rollbackTo(t)}async rollbackSingleFile(e,t){return (await this.getCheckpoint(e)).rollbackSingleFile(t)}async reapplySingleFile(e,t){return (await this.getCheckpoint(e)).reapplySingleFile(t)}async getCheckpoints(e,t,s){return (await this.getCheckpoint(e)).getCheckpoints(t,s)}async getDiff(e,t,s){return (await this.getCheckpoint(e)).getDiff(t,s)}async getChangeBuffer(e){return (await this.getCheckpoint(e)).getChangeBuffer()}async getCurrentStats(e){return (await this.getCheckpoint(e)).getCurrentStats()}async onFileChange(e,t){return (await this.getCheckpoint(e)).onFileChange(t)}isWatching(e){let t=te.normalize(e);return this.instances.get(t)?.isActive()??false}async cleanup(e){let t=te.normalize(e),s=this.instances.get(t);s&&(await s.destroy(),this.instances.delete(t));let n=te.join(t,".cdundo");try{await ce.rm(n,{recursive:!0,force:!0}),console.log("[CheckpointManager] Cleaned up:",n);}catch(r){console.error("[CheckpointManager] Failed to cleanup:",r);}}async destroyAll(){for(let[e,t]of this.instances)await t.destroy();this.instances.clear(),console.log("[CheckpointManager] All instances destroyed");}getActiveWorkspaces(){return Array.from(this.instances.keys()).filter(e=>this.instances.get(e)?.isActive())}getStats(){return {totalInstances:this.instances.size,activeInstances:this.getActiveWorkspaces().length,workspaces:Array.from(this.instances.keys())}}};Mr.getInstance();var zo=class{checkpointManager;workspacePath=null;enabled=true;sessionMessageCounts=new Map;constructor(e){this.checkpointManager=e??Mr.getInstance();}setWorkspace(e){this.workspacePath=e;}setEnabled(e){this.enabled=e;}isEnabled(){return this.enabled}async startMessage(e){if(!this.enabled||!this.workspacePath)return null;let t=this.sessionMessageCounts.get(e)||0;return this.checkpointManager.startWatching(this.workspacePath,e,t)}async finishMessage(e,t){if(!this.enabled||!this.workspacePath)return null;let s=await this.createCheckpoint(e,t);return await this.checkpointManager.stopWatching(this.workspacePath),s}async stopWatching(){this.workspacePath&&await this.checkpointManager.stopWatching(this.workspacePath);}async createCheckpoint(e,t){if(!this.enabled||!this.workspacePath)return null;let s=this.sessionMessageCounts.get(e)||0,n=t||`Message #${s+1}`,r=await this.checkpointManager.createCheckpoint(this.workspacePath,n);return this.sessionMessageCounts.set(e,s+1),r}async rollbackToCheckpoint(e){return this.workspacePath?this.checkpointManager.rollbackTo(this.workspacePath,e):{success:false,restored:[],errors:["No workspace set"]}}async rollbackSingleFile(e){return this.workspacePath?this.checkpointManager.rollbackSingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async reapplySingleFile(e){return this.workspacePath?this.checkpointManager.reapplySingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async getCheckpoints(e,t){return this.workspacePath?this.checkpointManager.getCheckpoints(this.workspacePath,e,t):[]}async getCurrentStats(){return this.workspacePath?this.checkpointManager.getCurrentStats(this.workspacePath):null}async getChangeBuffer(){return this.workspacePath?this.checkpointManager.getChangeBuffer(this.workspacePath):[]}async cleanup(){this.workspacePath&&await this.checkpointManager.cleanup(this.workspacePath);}};function ik(){throw new Error("Approval prompt is not configured");}async function Qm(a){let{toolName:e,args:t,reason:s,allowRemember:n}=a,r=ik(),i=Object.keys(t).length>0?` (${Object.keys(t).slice(0,2).join(", ")}${Object.keys(t).length>2?"...":""})`:"",o=`Allow tool ${e}${i}?`,l=s?`Warning: ${s}`:void 0,c=[{label:"Allow Once",value:"allow_once",description:"Allow this tool call only this time"}];switch(n&&c.push({label:"Always Allow",value:"always_allow",description:`Don't ask again for "${e}"`}),c.push({label:"Deny",value:"deny",description:"Reject this tool call"}),await r(o,c,"allow_once",l)){case "allow_once":return {approved:true,remember:false};case "always_allow":return {approved:true,remember:true};case "deny":return {approved:false,remember:false};default:return {approved:false,remember:false}}}function Zm(a="auto"){let e=a==="dangerous",t=a==="manual",s=new ls({approvalHandler:e?void 0:Qm,defaultPermission:e?"allow":t?"ask":"allow",memoryExpirationMs:1440*60*1e3});return e||_l(s),s}W();var ak=te__default.join(vs,"workspaces"),lk=200,ck=20,uk=50,dk=40,pk=4e3,$c=8,mk=240,gk=8,hk=256*1024,Fc=6,Pr=240,eg=512*1024,fk=1500,yk=15e3,bk=6,vk=30,wk="claude-haiku";function Ck(a){return a.toLowerCase().replace(/[^a-z0-9-_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,24)||"workspace"}function kk(a){let e=te__default.resolve(a),t=Ck(te__default.basename(e)),s=Yt.createHash("sha1").update(e).digest("hex").slice(0,12);return `${t}-${s}`}function Sk(a){return new Date(a).toISOString().slice(0,10)}function Dr(a){let e=new Date(a),t=s=>String(s).padStart(2,"0");return [e.getFullYear(),t(e.getMonth()+1),t(e.getDate())].join("-")+` ${t(e.getHours())}:${t(e.getMinutes())}`}function ot(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var Lr=class{options;workspacePath=null;workspaceId=null;workspaceName=null;eventsDir=null;memoriesDir=null;memoryPaths=null;graphPaths=null;indexPath=null;summaryPath=null;sessionSummaryPath=null;metaPath=null;seq=0;currentDate=null;currentFile=null;currentFileBytes=0;queue=[];sessionSummaryQueue=[];memoryQueue=[];graphNodeQueue=[];graphEdgeQueue=[];summarizerOverrides;summarizerQueue=[];summarizerTimer=null;summarizerRunning=false;summarizerLastRun=0;summarizerProvider=null;summarizerProviderModel=null;summaryItems=[];summaryDirty=false;runAggregates=new Map;flushTimer=null;isFlushing=false;flushPending=false;ready=false;initPromise=null;createdAt=Date.now();constructor(e={}){this.options={flushIntervalMs:e.flushIntervalMs??lk,batchSize:e.batchSize??ck,indexStride:e.indexStride??uk,summaryWindow:e.summaryWindow??dk,maxSummaryChars:e.maxSummaryChars??pk,source:e.source,agentName:e.agentName},this.summarizerOverrides=e.summarizer,e.workspacePath&&this.setWorkspace(e.workspacePath);}async setWorkspace(e){let t=te__default.resolve(e);if(this.workspacePath===t)return;await this.flush(),this.workspacePath=t,this.workspaceName=te__default.basename(t),this.workspaceId=kk(t);let s=te__default.join(ak,this.workspaceId);this.eventsDir=te__default.join(s,"events"),this.memoriesDir=te__default.join(s,"memories"),this.memoryPaths={progress:te__default.join(this.memoriesDir,"progress.jsonl"),standard:te__default.join(this.memoriesDir,"standards.jsonl"),lesson:te__default.join(this.memoriesDir,"lessons.jsonl"),pinned:te__default.join(this.memoriesDir,"pinned.jsonl")},this.graphPaths={nodes:te__default.join(this.memoriesDir,"graph_nodes.jsonl"),edges:te__default.join(this.memoriesDir,"graph_edges.jsonl")},this.indexPath=te__default.join(this.eventsDir,"index.jsonl"),this.summaryPath=te__default.join(this.eventsDir,"recent_summary.json"),this.sessionSummaryPath=this.memoriesDir?te__default.join(this.memoriesDir,"session_summary.jsonl"):null,this.metaPath=te__default.join(this.eventsDir,"meta.json"),this.currentDate=null,this.currentFile=null,this.currentFileBytes=0,this.sessionSummaryQueue=[],this.memoryQueue=[],this.graphNodeQueue=[],this.graphEdgeQueue=[],this.summarizerQueue=[],this.summarizerProvider=null,this.summarizerProviderModel=null,this.runAggregates.clear(),this.ready=false,this.initPromise=this.initializeWorkspace(),await this.initPromise;}formatFilePath(e){if(!this.workspacePath)return e;let t=te__default.relative(this.workspacePath,e);return !t||t.startsWith("..")?e:t}record(e){if(!this.workspacePath||!this.workspaceId)return;let t={schemaVersion:1,id:Yt.randomUUID(),seq:++this.seq,ts:e.ts??Date.now(),workspaceId:this.workspaceId,workspacePath:this.workspacePath,type:e.type,sessionId:e.sessionId,runId:e.runId,actor:e.actor,summary:e.summary,reason:e.reason,files:e.files,data:e.data};this.queue.push(t),this.updateSummary(t),this.updateRunAggregate(t),this.maybeQueueSessionSummary(t),this.queueMemoryEntries(this.extractMemoryEntries(t),"event"),this.queueGraphEntries(this.extractGraphEntries(t));let s=t.type==="run_result"||t.type==="run_error";(this.queue.length>=this.options.batchSize||s)&&this.flush();}createRunId(){return Yt.randomUUID()}async getContextSummary(e){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let t=e?.language??"zh",s=e?.maxItems??this.options.summaryWindow,n=e?.maxSessionItems??$c,r=e?.maxMemoryItems??Fc,i=e?.maxChars??this.options.maxSummaryChars,o=e?.query?.trim(),l=t==="zh"?{memoryHeader:"## \u9879\u76EE\u8BB0\u5FC6\uFF08\u81EA\u52A8\uFF09",pinned:"### \u56FA\u5B9A",progress:"### \u8FDB\u5EA6",standard:"### \u89C4\u8303",lesson:"### \u6559\u8BAD",sessionHeader:"## \u4F1A\u8BDD\u6458\u8981",activityHeader:"## \u6700\u8FD1\u5DE5\u4F5C\u6458\u8981"}:{memoryHeader:"## Project Memory (Auto)",pinned:"### Pinned",progress:"### Progress",standard:"### Standards",lesson:"### Lessons",sessionHeader:"## Session Summary",activityHeader:"## Recent Workspace Activity"},c=null;if(o){let I=this.tokenizeQuery(o);c={tokens:I,graphMatches:await this.getGraphRunMatches(I)};}let u=o&&c?await this.getRelevantSessionSummaries(o,n,c):await this.getRecentSessionSummaries(n),d=o&&c?await this.getRelevantMemoryItems(o,r,c):{pinned:await this.getRecentMemoryItems("pinned",r),progress:await this.getRecentMemoryItems("progress",r),standard:await this.getRecentMemoryItems("standard",r),lesson:await this.getRecentMemoryItems("lesson",r)},p=d.pinned,h=d.progress,g=d.standard,f=d.lesson,b=this.summaryItems.slice(-s),y=I=>I.map(A=>`- [${Dr(A.ts)}] ${A.summary}`),w=y(u),C=y(p),k=y(h),T=y(g),_=y(f),M=y(b),F=[{key:"pinned",title:l.pinned,lines:C},{key:"progress",title:l.progress,lines:k},{key:"standard",title:l.standard,lines:T},{key:"lesson",title:l.lesson,lines:_}],x={key:"activity",title:l.activityHeader,lines:M},R={key:"session",title:l.sessionHeader,lines:w};if(F.every(I=>I.lines.length===0)&&w.length===0&&M.length===0)return null;let j=()=>{let I=[],A=F.filter(O=>O.lines.length>0).map(O=>`${O.title}
3362
3362
  ${O.lines.join(`
3363
3363
  `)}`);return A.length>0&&I.push(`${l.memoryHeader}
3364
3364
  ${A.join(`
@@ -3376,7 +3376,7 @@ ${f.join(`
3376
3376
  `)}`),g.length>0&&k.push(`${u.lastRunHeader}
3377
3377
  ${g.join(`
3378
3378
  `)}`),k.join(`
3379
- `)},y=["session","lastRun","lesson","standard","progress","pinned"],w=new Map([["session",{lines:f}],["lastRun",{lines:g}],...p.map(k=>[k.key,k])]),C=b();if(C.length>r){let k=0;for(;C.length>r&&k<500;){k+=1;let T=false;for(let _ of y){let M=w.get(_);if(M&&M.lines.length>0){M.lines.shift(),T=true;break}}if(!T)break;C=b();}}return C.length>r&&(C=ot(C,r)),m.info("MEMORY_INJECT","Context memory hit",{query:c?ot(c,80):void 0,includePersistent:i,includeLastRun:o,includeSessionSummaries:l,memoryCounts:Object.fromEntries(p.map(k=>[k.key,k.lines.length])),sessionCount:f.length,lastRun:g.length>0,summaryChars:C.length}),C}async getMemoryStats(){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let e=this.summaryItems.length,t=this.summaryPath?await this.getFileSize(this.summaryPath):0,s=this.sessionSummaryPath?await this.countJsonlLines(this.sessionSummaryPath):0,n=this.sessionSummaryPath?await this.getFileSize(this.sessionSummaryPath):0,r=this.memoryPaths?.progress,i=this.memoryPaths?.standard,o=this.memoryPaths?.lesson,l=this.memoryPaths?.pinned,c=r?await this.countJsonlLines(r):0,u=i?await this.countJsonlLines(i):0,d=o?await this.countJsonlLines(o):0,p=l?await this.countJsonlLines(l):0,h=r?await this.getFileSize(r):0,g=i?await this.getFileSize(i):0,f=o?await this.getFileSize(o):0,b=l?await this.getFileSize(l):0,y=c+u+d,w=h+g+f,C=e+s+y+p,k=t+n+w+b,T=(_,M,F)=>({count:_,sizeBytes:M,path:F});return {shortTerm:T(e,t,this.summaryPath??void 0),session:T(s,n,this.sessionSummaryPath??void 0),longTerm:{total:T(y,w),progress:T(c,h,r),standard:T(u,g,i),lesson:T(d,f,o)},pinned:T(p,b,l),totals:T(C,k)}}async getRecentSessionSummaries(e=$c){return await this.ensureReady(),this.sessionSummaryPath?this.readJsonlTail(this.sessionSummaryPath,e):[]}async getRecentEventSummaries(e){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let t=e?.maxItems??this.options.summaryWindow,s=this.summaryItems;return e?.sessionId&&(s=s.filter(n=>n.sessionId===e.sessionId)),e?.runId&&(s=s.filter(n=>n.runId===e.runId)),s.length<=t?s:s.slice(s.length-t)}async getLastMeaningfulSessionSummary(){if(!this.sessionSummaryPath)return null;let e=await this.readJsonlTail(this.sessionSummaryPath,8);if(e.length===0)return null;for(let t=e.length-1;t>=0;t-=1)if(!this.isMetaQuerySummary(e[t].summary))return e[t];return e[e.length-1]??null}isMetaQuerySummary(e){if(!e)return false;let t=e.trim().toLowerCase();return /(user:|用户:)?\s*(上次|之前|前面|上一|继续|回顾|resume|continue|previous|last)/i.test(t)}stripUserPrefix(e){return e.replace(/^(user|用户)\s*[::]\s*/i,"").trim()}isGreeting(e){let t=e.trim().toLowerCase();return !t||/^(hi|hello|hey|yo|good (morning|afternoon|evening))\b/i.test(t)?true:["\u4F60\u597D","\u60A8\u597D","\u54C8\u55BD","\u55E8","\u5728\u5417","\u65E9\u4E0A\u597D","\u4E0B\u5348\u597D","\u665A\u4E0A\u597D","\u665A\u5B89"].some(r=>t.startsWith(r))}isLowValuePrompt(e){let t=this.stripUserPrefix(e);return !t||this.isGreeting(t)||this.isMetaQuerySummary(t)?true:t.length<=2}isLowValueMemorySummary(e){let t=this.stripUserPrefix(e);return !t||this.isGreeting(t)||this.isMetaQuerySummary(t)?true:/(会话已建立|打招呼|session (started|created))/i.test(t)}isLowValueToolFailure(e,t){let s=e.toLowerCase(),n=t.toLowerCase();return !!((s.includes("git_status")||s.includes("git status")||s.includes("gitstatus"))&&n.includes("not a git repository"))}async getRecentMemoryItems(e,t=Fc){if(await this.ensureReady(),!this.memoryPaths)return [];let s=this.memoryPaths[e];return this.readJsonlTail(s,t)}async getRelevantSessionSummaries(e,t,s){if(!this.sessionSummaryPath)return [];let n=await this.readJsonlTail(this.sessionSummaryPath,t*6);return this.rankRelevantItems(n,e,t,void 0,s)}async getRelevantMemoryItems(e,t,s){if(!this.memoryPaths)return {progress:[],standard:[],lesson:[],pinned:[]};let n=["pinned","progress","standard","lesson"],r={pinned:[],progress:[],standard:[],lesson:[]};for(let i of n){let o=await this.readJsonlTail(this.memoryPaths[i],t*6);r[i]=await this.rankRelevantItems(o,e,t,i,s);}return r}async rankRelevantItems(e,t,s,n,r){let i=r?.tokens??this.tokenizeQuery(t);if(i.length===0)return e.slice(-s);let o=r?.graphMatches??await this.getGraphRunMatches(i),l=Date.now(),c=e.map(u=>{let d=this.scoreLexical(i,u.summary),p=this.scorePath(i,u.files),h=this.scoreRecency(l,u.ts),g=u.confidence??.5,f=u.runId&&o.has(u.runId)?1:0,b=u.summary&&u.summary.length>0?1:0,y=.35*d+.2*p+.2*f+.15*h+.1*g;return n==="pinned"&&y<.2&&(y=.2),b===0&&(y*=.8),{item:u,score:y}});return await this.applyEvidencePenalty(c,s),c.sort((u,d)=>d.score-u.score),c.filter(u=>u.score>0).slice(0,s).map(u=>u.item)}async applyEvidencePenalty(e,t){if(!this.workspacePath)return;let s=e.slice(0,Math.min(e.length,t*2));for(let n of s){let r=n.item.files?.[0];if(!r)continue;let i=this.resolveWorkspacePath(r);try{await ce__default.stat(i);}catch{n.score*=.7;}}}resolveWorkspacePath(e){return te__default.isAbsolute(e)||!this.workspacePath?e:te__default.join(this.workspacePath,e)}tokenizeQuery(e){let t=e.trim().toLowerCase();if(!t)return [];let s=t.split(/[^a-z0-9/_\-.]+/g).map(n=>n.trim()).filter(n=>n.length>2);return s.length===0&&t.length>0?[t]:s.slice(0,16)}scoreLexical(e,t){if(!t)return 0;let s=t.toLowerCase(),n=0;for(let r of e)s.includes(r)&&(n+=1);return n===0?0:Math.min(1,n/e.length)}scorePath(e,t){if(!t||t.length===0)return 0;let s=0;for(let n of t){let r=n.toLowerCase();for(let i of e)if(r.includes(i)){s+=1;break}}return s===0?0:Math.min(1,s/t.length)}scoreRecency(e,t){let n=Math.max(0,e-t)/(1440*60*1e3);return Math.exp(-Math.log(2)*n/7)}async getGraphRunMatches(e){if(!this.graphPaths||e.length===0)return new Set;let t=await this.readJsonlTail(this.graphPaths.nodes,4e3,{tailBytes:eg,requireSummary:false}),s=new Set;for(let i of t){if(!i?.label)continue;let o=i.label.toLowerCase();for(let l of e)if(o.includes(l)){s.add(i.id);break}}if(s.size===0)return new Set;let n=await this.readJsonlTail(this.graphPaths.edges,6e3,{tailBytes:eg,requireSummary:false}),r=new Set;for(let i of n)i?.runId&&(s.has(i.to)||s.has(i.from))&&r.add(i.runId);return r}async readJsonlTail(e,t,s){let n=s?.tailBytes??gk,r=s?.requireSummary??true;try{let i=await ce__default.stat(e);if(i.size===0)return [];let o=Math.max(0,i.size-n),l=await ce__default.open(e,"r");try{let c=Buffer.alloc(i.size-o);await l.read(c,0,c.length,o);let u=c.toString("utf-8");if(o>0){let h=u.indexOf(`
3379
+ `)},y=["session","lastRun","lesson","standard","progress","pinned"],w=new Map([["session",{lines:f}],["lastRun",{lines:g}],...p.map(k=>[k.key,k])]),C=b();if(C.length>r){let k=0;for(;C.length>r&&k<500;){k+=1;let T=false;for(let _ of y){let M=w.get(_);if(M&&M.lines.length>0){M.lines.shift(),T=true;break}}if(!T)break;C=b();}}return C.length>r&&(C=ot(C,r)),m.info("MEMORY_INJECT","Context memory hit",{query:c?ot(c,80):void 0,includePersistent:i,includeLastRun:o,includeSessionSummaries:l,memoryCounts:Object.fromEntries(p.map(k=>[k.key,k.lines.length])),sessionCount:f.length,lastRun:g.length>0,summaryChars:C.length}),C}async getMemoryStats(){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let e=this.summaryItems.length,t=this.summaryPath?await this.getFileSize(this.summaryPath):0,s=this.sessionSummaryPath?await this.countJsonlLines(this.sessionSummaryPath):0,n=this.sessionSummaryPath?await this.getFileSize(this.sessionSummaryPath):0,r=this.memoryPaths?.progress,i=this.memoryPaths?.standard,o=this.memoryPaths?.lesson,l=this.memoryPaths?.pinned,c=r?await this.countJsonlLines(r):0,u=i?await this.countJsonlLines(i):0,d=o?await this.countJsonlLines(o):0,p=l?await this.countJsonlLines(l):0,h=r?await this.getFileSize(r):0,g=i?await this.getFileSize(i):0,f=o?await this.getFileSize(o):0,b=l?await this.getFileSize(l):0,y=c+u+d,w=h+g+f,C=e+s+y+p,k=t+n+w+b,T=(_,M,F)=>({count:_,sizeBytes:M,path:F});return {shortTerm:T(e,t,this.summaryPath??void 0),session:T(s,n,this.sessionSummaryPath??void 0),longTerm:{total:T(y,w),progress:T(c,h,r),standard:T(u,g,i),lesson:T(d,f,o)},pinned:T(p,b,l),totals:T(C,k)}}async getRecentSessionSummaries(e=$c){return await this.ensureReady(),this.sessionSummaryPath?this.readJsonlTail(this.sessionSummaryPath,e):[]}async getRecentEventSummaries(e){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let t=e?.maxItems??this.options.summaryWindow,s=this.summaryItems;return e?.sessionId&&(s=s.filter(n=>n.sessionId===e.sessionId)),e?.runId&&(s=s.filter(n=>n.runId===e.runId)),s.length<=t?s:s.slice(s.length-t)}async getLastMeaningfulSessionSummary(){if(!this.sessionSummaryPath)return null;let e=await this.readJsonlTail(this.sessionSummaryPath,8);if(e.length===0)return null;for(let t=e.length-1;t>=0;t-=1)if(!this.isMetaQuerySummary(e[t].summary))return e[t];return e[e.length-1]??null}isMetaQuerySummary(e){if(!e)return false;let t=e.trim().toLowerCase();return /(user:|用户:)?\s*(上次|之前|前面|上一|继续|回顾|resume|continue|previous|last)/i.test(t)}stripUserPrefix(e){return e.replace(/^(user|用户)\s*[::]\s*/i,"").trim()}isGreeting(e){let t=e.trim().toLowerCase();return !t||/^(hi|hello|hey|yo|good (morning|afternoon|evening))\b/i.test(t)?true:["\u4F60\u597D","\u60A8\u597D","\u54C8\u55BD","\u55E8","\u5728\u5417","\u65E9\u4E0A\u597D","\u4E0B\u5348\u597D","\u665A\u4E0A\u597D","\u665A\u5B89"].some(r=>t.startsWith(r))}isLowValuePrompt(e){let t=this.stripUserPrefix(e);return !t||this.isGreeting(t)||this.isMetaQuerySummary(t)?true:t.length<=2}isLowValueMemorySummary(e){let t=this.stripUserPrefix(e);return !t||this.isGreeting(t)||this.isMetaQuerySummary(t)?true:/(会话已建立|打招呼|session (started|created))/i.test(t)}isLowValueToolFailure(e,t){let s=e.toLowerCase(),n=t.toLowerCase();return !!((s.includes("git_status")||s.includes("git status")||s.includes("gitstatus"))&&n.includes("not a git repository"))}async getRecentMemoryItems(e,t=Fc){if(await this.ensureReady(),!this.memoryPaths)return [];let s=this.memoryPaths[e];return this.readJsonlTail(s,t)}async getRelevantSessionSummaries(e,t,s){if(!this.sessionSummaryPath)return [];let n=await this.readJsonlTail(this.sessionSummaryPath,t*6);return this.rankRelevantItems(n,e,t,void 0,s)}async getRelevantMemoryItems(e,t,s){if(!this.memoryPaths)return {progress:[],standard:[],lesson:[],pinned:[]};let n=["pinned","progress","standard","lesson"],r={pinned:[],progress:[],standard:[],lesson:[]};for(let i of n){let o=await this.readJsonlTail(this.memoryPaths[i],t*6);r[i]=await this.rankRelevantItems(o,e,t,i,s);}return r}async rankRelevantItems(e,t,s,n,r){let i=r?.tokens??this.tokenizeQuery(t);if(i.length===0)return e.slice(-s);let o=r?.graphMatches??await this.getGraphRunMatches(i),l=Date.now(),c=e.map(u=>{let d=this.scoreLexical(i,u.summary),p=this.scorePath(i,u.files),h=this.scoreRecency(l,u.ts),g=u.confidence??.5,f=u.runId&&o.has(u.runId)?1:0,b=u.summary&&u.summary.length>0?1:0,y=.35*d+.2*p+.2*f+.15*h+.1*g;return n==="pinned"&&y<.2&&(y=.2),b===0&&(y*=.8),{item:u,score:y}});return await this.applyEvidencePenalty(c,s),c.sort((u,d)=>d.score-u.score),c.filter(u=>u.score>0).slice(0,s).map(u=>u.item)}async applyEvidencePenalty(e,t){if(!this.workspacePath)return;let s=e.slice(0,Math.min(e.length,t*2));for(let n of s){let r=n.item.files?.[0];if(!r)continue;let i=this.resolveWorkspacePath(r);try{await ce__default.stat(i);}catch{n.score*=.7;}}}resolveWorkspacePath(e){return te__default.isAbsolute(e)||!this.workspacePath?e:te__default.join(this.workspacePath,e)}tokenizeQuery(e){let t=e.trim().toLowerCase();if(!t)return [];let s=t.split(/[^a-z0-9/_\-.]+/g).map(n=>n.trim()).filter(n=>n.length>2);return s.length===0&&t.length>0?[t]:s.slice(0,16)}scoreLexical(e,t){if(!t)return 0;let s=t.toLowerCase(),n=0;for(let r of e)s.includes(r)&&(n+=1);return n===0?0:Math.min(1,n/e.length)}scorePath(e,t){if(!t||t.length===0)return 0;let s=0;for(let n of t){let r=n.toLowerCase();for(let i of e)if(r.includes(i)){s+=1;break}}return s===0?0:Math.min(1,s/t.length)}scoreRecency(e,t){let n=Math.max(0,e-t)/(1440*60*1e3);return Math.exp(-Math.log(2)*n/7)}async getGraphRunMatches(e){if(!this.graphPaths||e.length===0)return new Set;let t=await this.readJsonlTail(this.graphPaths.nodes,4e3,{tailBytes:eg,requireSummary:false}),s=new Set;for(let i of t){if(!i?.label)continue;let o=i.label.toLowerCase();for(let l of e)if(o.includes(l)){s.add(i.id);break}}if(s.size===0)return new Set;let n=await this.readJsonlTail(this.graphPaths.edges,6e3,{tailBytes:eg,requireSummary:false}),r=new Set;for(let i of n)i?.runId&&(s.has(i.to)||s.has(i.from))&&r.add(i.runId);return r}async readJsonlTail(e,t,s){let n=s?.tailBytes??hk,r=s?.requireSummary??true;try{let i=await ce__default.stat(e);if(i.size===0)return [];let o=Math.max(0,i.size-n),l=await ce__default.open(e,"r");try{let c=Buffer.alloc(i.size-o);await l.read(c,0,c.length,o);let u=c.toString("utf-8");if(o>0){let h=u.indexOf(`
3380
3380
  `);h!==-1&&(u=u.slice(h+1));}let d=u.split(`
3381
3381
  `).filter(h=>h.trim().length>0),p=[];for(let h of d)try{let g=JSON.parse(h);r?g?.summary&&p.push(g):p.push(g);}catch{}return p.slice(-t)}finally{await l.close();}}catch{return []}}async countJsonlLines(e){return new Promise(t=>{let s=0,n="",r=false,i=createReadStream(e,{encoding:"utf-8"});i.on("data",o=>{let l=typeof o=="string"?o:o.toString("utf-8");r=true;for(let c=0;c<l.length;c+=1)l[c]===`
3382
3382
  `&&(s+=1);n=l[l.length-1]||n;}),i.on("error",o=>{o.code,t(0);}),i.on("end",()=>{r&&n!==`
@@ -3390,7 +3390,7 @@ ${g.join(`
3390
3390
  `)+`
3391
3391
  `;await ce__default.appendFile(this.graphPaths.nodes,c,"utf-8");}if(r.length>0){let c=r.map(u=>JSON.stringify(u)).join(`
3392
3392
  `)+`
3393
- `;await ce__default.appendFile(this.graphPaths.edges,c,"utf-8");}}}finally{this.isFlushing=false,this.flushPending&&(this.flushPending=false,await this.flush());}}}async shutdown(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.summarizerTimer&&(clearTimeout(this.summarizerTimer),this.summarizerTimer=null),await this.flush();}async initializeWorkspace(){!this.eventsDir||!this.workspaceId||!this.workspacePath||(await ce__default.mkdir(this.eventsDir,{recursive:true}),this.memoriesDir&&await ce__default.mkdir(this.memoriesDir,{recursive:true}),await this.loadMeta(),await this.loadSummarySnapshot(),this.ensureFlushTimer(),this.ready=true);}ensureFlushTimer(){this.flushTimer||(this.flushTimer=setInterval(()=>{this.flush();},this.options.flushIntervalMs));}async ensureReady(){this.ready||this.initPromise&&await this.initPromise;}async ensureLogFile(){if(!this.eventsDir)return;let e=kk(Date.now());this.currentDate===e&&this.currentFile||(this.currentDate=e,this.currentFile=te__default.join(this.eventsDir,`events-${e}.jsonl`),this.currentFileBytes=await this.getFileSize(this.currentFile));}async getFileSize(e){try{return (await ce__default.stat(e)).size}catch{return 0}}updateSummary(e){e.summary&&(this.summaryItems.push({id:e.id,ts:e.ts,type:e.type,summary:e.summary,files:e.files,sessionId:e.sessionId,runId:e.runId}),this.summaryItems.length>this.options.summaryWindow&&this.summaryItems.splice(0,this.summaryItems.length-this.options.summaryWindow),this.summaryDirty=true);}queueMemoryEntries(e,t){if(!e.length)return;let s=e.filter(n=>!this.isLowValueMemorySummary(n.summary));if(s.length!==0){this.memoryQueue.push(...s);for(let n of s)m.info("MEMORY_WRITE","Memory item recorded",{source:t,category:n.category,summary:ot(n.summary,160),runId:n.runId,sessionId:n.sessionId,files:n.files?.slice(0,3),confidence:n.confidence});}}queueGraphEntries(e){e.nodes.length>0&&this.graphNodeQueue.push(...e.nodes),e.edges.length>0&&this.graphEdgeQueue.push(...e.edges);}extractMemoryEntries(e){let t=[],s={ts:e.ts,sessionId:e.sessionId,runId:e.runId,files:e.files,evidence:{eventId:e.id}};if(e.type==="plan_update"&&e.summary&&t.push({schemaVersion:1,id:Yt.randomUUID(),category:"progress",summary:ot(e.summary,Pr),confidence:.6,...s}),e.type==="tool_call_end"&&e.data?.success===false){let n=e.data?.name??"tool",r=e.data?.outputPreview??e.summary??"Tool failed";this.isLowValueToolFailure(n,String(r))||t.push({schemaVersion:1,id:Yt.randomUUID(),category:"lesson",summary:ot(`Tool failed: ${n} - ${r}`,Pr),confidence:.45,...s});}if(e.type==="run_error"){let n=e.data?.message??e.summary??"Run error";t.push({schemaVersion:1,id:Yt.randomUUID(),category:"lesson",summary:ot(`Run error: ${n}`,Pr),confidence:.4,...s});}if(e.type==="status"&&e.summary){let n=this.extractRuleMemory(e.summary);n&&t.push({schemaVersion:1,id:Yt.randomUUID(),category:n.category,summary:ot(n.summary,Pr),confidence:n.confidence,...s});}return t}extractGraphEntries(e){let t=[],s=[];if(!this.graphPaths||!e.runId)return {nodes:t,edges:s};let n=this.buildGraphNode({id:`task:${e.runId}`,type:"task",label:ot(e.summary??e.data?.prompt??"Task",120),event:e});if(e.type==="run_start"&&t.push(n),e.type==="tool_call_start"){let r=e.data?.name;if(r){let i=this.buildGraphNode({id:`tool:${r}`,type:"tool",label:r,event:e});t.push(i),s.push(this.buildGraphEdge({type:"uses",from:n.id,to:i.id,event:e}));}}if(e.type==="file_change"&&e.files?.length)for(let r of e.files){let i=this.buildGraphNode({id:`file:${r}`,type:"file",label:r,event:e});t.push(i),s.push(this.buildGraphEdge({type:"touches",from:n.id,to:i.id,event:e}));}return {nodes:t,edges:s}}buildGraphNode(e){return {schemaVersion:1,id:e.id,type:e.type,label:e.label,ts:e.event.ts,sessionId:e.event.sessionId,runId:e.event.runId,evidence:{eventId:e.event.id}}}buildGraphEdge(e){return {schemaVersion:1,id:Yt.randomUUID(),type:e.type,from:e.from,to:e.to,ts:e.event.ts,sessionId:e.event.sessionId,runId:e.event.runId,evidence:{eventId:e.event.id}}}extractRuleMemory(e){let t=e.trim();if(!t)return null;let s=t.toLowerCase(),n=/^(pinned|must|requirement|constraint|must:|禁止|必须|约束|不可)/i,r=/^(rule|standard|guideline|should|prefer|规范|约定|标准|建议|应该)/i;return n.test(s)?{category:"pinned",summary:t,confidence:.8}:r.test(s)?{category:"standard",summary:t,confidence:.65}:null}getSummarizerConfig(){let e=Oe(),t=e.memory??{},s=e.orchestrator?.contextSharing?.summarizerModel,n,r="default";return this.summarizerOverrides?.model?(n=this.summarizerOverrides.model,r="override"):t.summarizerModel?(n=t.summarizerModel,r="memory"):s?(n=s,r="orchestrator"):(n=vk,r="default"),{enabled:(this.summarizerOverrides?.enabled??t.summarizerEnabled??true)&&!!n,model:n??null,providerId:this.summarizerOverrides?.providerId??t.summarizerProviderId,idleDelayMs:this.summarizerOverrides?.idleDelayMs??t.summarizerIdleMs??hk,minIntervalMs:this.summarizerOverrides?.minIntervalMs??t.summarizerMinIntervalMs??fk,batchSize:this.summarizerOverrides?.batchSize??t.summarizerBatchSize??yk,queueSize:this.summarizerOverrides?.queueSize??t.summarizerQueueSize??bk,modelSource:r}}enqueueSummarizer(e){let t=this.getSummarizerConfig();t.enabled&&(this.summarizerQueue.push(e),this.summarizerQueue.length>t.queueSize&&this.summarizerQueue.splice(0,this.summarizerQueue.length-t.queueSize),this.scheduleSummarizer(t));}scheduleSummarizer(e){this.summarizerTimer||(this.summarizerTimer=setTimeout(()=>{this.runSummarizer();},e.idleDelayMs));}async runSummarizer(){this.summarizerTimer&&(clearTimeout(this.summarizerTimer),this.summarizerTimer=null);let e=this.getSummarizerConfig();if(!e.enabled){this.summarizerQueue=[];return}if(this.summarizerRunning){this.scheduleSummarizer(e);return}let t=Date.now(),s=e.minIntervalMs-(t-this.summarizerLastRun);if(s>0){this.summarizerTimer=setTimeout(()=>{this.runSummarizer();},s);return}let n=this.summarizerQueue.splice(0,e.batchSize);if(n.length===0)return;let r=this.resolveSummarizerProvider(e);if(!r){this.summarizerQueue=[],this.summarizerLastRun=t;return}this.summarizerRunning=true;try{let i=await this.summarizeMemoryBatch(r.provider,r.model,n);i.length>0&&(this.queueMemoryEntries(i,"summarizer"),this.flush());}catch(i){console.warn("[ActionLog] Memory summarizer failed:",i);}finally{this.summarizerRunning=false,this.summarizerLastRun=Date.now(),this.summarizerQueue.length>0&&this.scheduleSummarizer(e);}}resolveSummarizerProvider(e){if(!e.model)return null;let t=new rt(Oe()),s=e.providerId?t.getProvider(e.providerId):void 0;if(s||(s=t.getProviders().find(o=>o.models?.some(l=>l.name===e.model))),s||(s=t.getDefaultProvider()),!s||!s.apiKey)return null;let n=s.models?.some(o=>o.name===e.model),r=e.model;if(!n){if(e.modelSource!=="default")return null;r=s.defaultModel||s.lastSelectedModel||s.models?.[0]?.name||e.model;}if(!r)return null;if(this.summarizerProvider&&this.summarizerProviderModel===r)return {provider:this.summarizerProvider,model:r};let{llmProvider:i}=ho({provider:s,model:r});return this.summarizerProvider=i,this.summarizerProviderModel=r,{provider:i,model:r}}async summarizeMemoryBatch(e,t,s){let n=this.buildMemorySummaryPrompt(s),r=[{role:"system",content:"You are a memory summarizer for an autonomous coding agent."},{role:"user",content:n}],o=(await e.chat(r,{model:t,temperature:.2})).choices[0]?.message?.content||"",l=this.parseSummaryItems(o);if(l.length===0)return [];let c=s[s.length-1],u=Date.now();return l.map(d=>({schemaVersion:1,id:Yt.randomUUID(),ts:u,category:d.category,summary:ot(d.summary,Pr),sessionId:c.sessionId,runId:c.runId,files:d.files&&d.files.length>0?d.files:c.files,confidence:d.confidence,evidence:c.evidence}))}buildMemorySummaryPrompt(e){return `\u8BF7\u4ECE\u4EE5\u4E0B session \u6458\u8981\u4E2D\u63D0\u53D6\u957F\u671F\u53EF\u590D\u7528\u7684\u8BB0\u5FC6\uFF0C\u8F93\u51FA JSON \u6570\u7EC4\uFF08\u53EA\u8F93\u51FA JSON\uFF0C\u4E0D\u8981\u591A\u4F59\u6587\u672C\uFF09\u3002
3393
+ `;await ce__default.appendFile(this.graphPaths.edges,c,"utf-8");}}}finally{this.isFlushing=false,this.flushPending&&(this.flushPending=false,await this.flush());}}}async shutdown(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.summarizerTimer&&(clearTimeout(this.summarizerTimer),this.summarizerTimer=null),await this.flush();}async initializeWorkspace(){!this.eventsDir||!this.workspaceId||!this.workspacePath||(await ce__default.mkdir(this.eventsDir,{recursive:true}),this.memoriesDir&&await ce__default.mkdir(this.memoriesDir,{recursive:true}),await this.loadMeta(),await this.loadSummarySnapshot(),this.ensureFlushTimer(),this.ready=true);}ensureFlushTimer(){this.flushTimer||(this.flushTimer=setInterval(()=>{this.flush();},this.options.flushIntervalMs));}async ensureReady(){this.ready||this.initPromise&&await this.initPromise;}async ensureLogFile(){if(!this.eventsDir)return;let e=Sk(Date.now());this.currentDate===e&&this.currentFile||(this.currentDate=e,this.currentFile=te__default.join(this.eventsDir,`events-${e}.jsonl`),this.currentFileBytes=await this.getFileSize(this.currentFile));}async getFileSize(e){try{return (await ce__default.stat(e)).size}catch{return 0}}updateSummary(e){e.summary&&(this.summaryItems.push({id:e.id,ts:e.ts,type:e.type,summary:e.summary,files:e.files,sessionId:e.sessionId,runId:e.runId}),this.summaryItems.length>this.options.summaryWindow&&this.summaryItems.splice(0,this.summaryItems.length-this.options.summaryWindow),this.summaryDirty=true);}queueMemoryEntries(e,t){if(!e.length)return;let s=e.filter(n=>!this.isLowValueMemorySummary(n.summary));if(s.length!==0){this.memoryQueue.push(...s);for(let n of s)m.info("MEMORY_WRITE","Memory item recorded",{source:t,category:n.category,summary:ot(n.summary,160),runId:n.runId,sessionId:n.sessionId,files:n.files?.slice(0,3),confidence:n.confidence});}}queueGraphEntries(e){e.nodes.length>0&&this.graphNodeQueue.push(...e.nodes),e.edges.length>0&&this.graphEdgeQueue.push(...e.edges);}extractMemoryEntries(e){let t=[],s={ts:e.ts,sessionId:e.sessionId,runId:e.runId,files:e.files,evidence:{eventId:e.id}};if(e.type==="plan_update"&&e.summary&&t.push({schemaVersion:1,id:Yt.randomUUID(),category:"progress",summary:ot(e.summary,Pr),confidence:.6,...s}),e.type==="tool_call_end"&&e.data?.success===false){let n=e.data?.name??"tool",r=e.data?.outputPreview??e.summary??"Tool failed";this.isLowValueToolFailure(n,String(r))||t.push({schemaVersion:1,id:Yt.randomUUID(),category:"lesson",summary:ot(`Tool failed: ${n} - ${r}`,Pr),confidence:.45,...s});}if(e.type==="run_error"){let n=e.data?.message??e.summary??"Run error";t.push({schemaVersion:1,id:Yt.randomUUID(),category:"lesson",summary:ot(`Run error: ${n}`,Pr),confidence:.4,...s});}if(e.type==="status"&&e.summary){let n=this.extractRuleMemory(e.summary);n&&t.push({schemaVersion:1,id:Yt.randomUUID(),category:n.category,summary:ot(n.summary,Pr),confidence:n.confidence,...s});}return t}extractGraphEntries(e){let t=[],s=[];if(!this.graphPaths||!e.runId)return {nodes:t,edges:s};let n=this.buildGraphNode({id:`task:${e.runId}`,type:"task",label:ot(e.summary??e.data?.prompt??"Task",120),event:e});if(e.type==="run_start"&&t.push(n),e.type==="tool_call_start"){let r=e.data?.name;if(r){let i=this.buildGraphNode({id:`tool:${r}`,type:"tool",label:r,event:e});t.push(i),s.push(this.buildGraphEdge({type:"uses",from:n.id,to:i.id,event:e}));}}if(e.type==="file_change"&&e.files?.length)for(let r of e.files){let i=this.buildGraphNode({id:`file:${r}`,type:"file",label:r,event:e});t.push(i),s.push(this.buildGraphEdge({type:"touches",from:n.id,to:i.id,event:e}));}return {nodes:t,edges:s}}buildGraphNode(e){return {schemaVersion:1,id:e.id,type:e.type,label:e.label,ts:e.event.ts,sessionId:e.event.sessionId,runId:e.event.runId,evidence:{eventId:e.event.id}}}buildGraphEdge(e){return {schemaVersion:1,id:Yt.randomUUID(),type:e.type,from:e.from,to:e.to,ts:e.event.ts,sessionId:e.event.sessionId,runId:e.event.runId,evidence:{eventId:e.event.id}}}extractRuleMemory(e){let t=e.trim();if(!t)return null;let s=t.toLowerCase(),n=/^(pinned|must|requirement|constraint|must:|禁止|必须|约束|不可)/i,r=/^(rule|standard|guideline|should|prefer|规范|约定|标准|建议|应该)/i;return n.test(s)?{category:"pinned",summary:t,confidence:.8}:r.test(s)?{category:"standard",summary:t,confidence:.65}:null}getSummarizerConfig(){let e=Oe(),t=e.memory??{},s=e.orchestrator?.contextSharing?.summarizerModel,n,r="default";return this.summarizerOverrides?.model?(n=this.summarizerOverrides.model,r="override"):t.summarizerModel?(n=t.summarizerModel,r="memory"):s?(n=s,r="orchestrator"):(n=wk,r="default"),{enabled:(this.summarizerOverrides?.enabled??t.summarizerEnabled??true)&&!!n,model:n??null,providerId:this.summarizerOverrides?.providerId??t.summarizerProviderId,idleDelayMs:this.summarizerOverrides?.idleDelayMs??t.summarizerIdleMs??fk,minIntervalMs:this.summarizerOverrides?.minIntervalMs??t.summarizerMinIntervalMs??yk,batchSize:this.summarizerOverrides?.batchSize??t.summarizerBatchSize??bk,queueSize:this.summarizerOverrides?.queueSize??t.summarizerQueueSize??vk,modelSource:r}}enqueueSummarizer(e){let t=this.getSummarizerConfig();t.enabled&&(this.summarizerQueue.push(e),this.summarizerQueue.length>t.queueSize&&this.summarizerQueue.splice(0,this.summarizerQueue.length-t.queueSize),this.scheduleSummarizer(t));}scheduleSummarizer(e){this.summarizerTimer||(this.summarizerTimer=setTimeout(()=>{this.runSummarizer();},e.idleDelayMs));}async runSummarizer(){this.summarizerTimer&&(clearTimeout(this.summarizerTimer),this.summarizerTimer=null);let e=this.getSummarizerConfig();if(!e.enabled){this.summarizerQueue=[];return}if(this.summarizerRunning){this.scheduleSummarizer(e);return}let t=Date.now(),s=e.minIntervalMs-(t-this.summarizerLastRun);if(s>0){this.summarizerTimer=setTimeout(()=>{this.runSummarizer();},s);return}let n=this.summarizerQueue.splice(0,e.batchSize);if(n.length===0)return;let r=this.resolveSummarizerProvider(e);if(!r){this.summarizerQueue=[],this.summarizerLastRun=t;return}this.summarizerRunning=true;try{let i=await this.summarizeMemoryBatch(r.provider,r.model,n);i.length>0&&(this.queueMemoryEntries(i,"summarizer"),this.flush());}catch(i){console.warn("[ActionLog] Memory summarizer failed:",i);}finally{this.summarizerRunning=false,this.summarizerLastRun=Date.now(),this.summarizerQueue.length>0&&this.scheduleSummarizer(e);}}resolveSummarizerProvider(e){if(!e.model)return null;let t=new rt(Oe()),s=e.providerId?t.getProvider(e.providerId):void 0;if(s||(s=t.getProviders().find(o=>o.models?.some(l=>l.name===e.model))),s||(s=t.getDefaultProvider()),!s||!s.apiKey)return null;let n=s.models?.some(o=>o.name===e.model),r=e.model;if(!n){if(e.modelSource!=="default")return null;r=s.defaultModel||s.lastSelectedModel||s.models?.[0]?.name||e.model;}if(!r)return null;if(this.summarizerProvider&&this.summarizerProviderModel===r)return {provider:this.summarizerProvider,model:r};let{llmProvider:i}=ho({provider:s,model:r});return this.summarizerProvider=i,this.summarizerProviderModel=r,{provider:i,model:r}}async summarizeMemoryBatch(e,t,s){let n=this.buildMemorySummaryPrompt(s),r=[{role:"system",content:"You are a memory summarizer for an autonomous coding agent."},{role:"user",content:n}],o=(await e.chat(r,{model:t,temperature:.2})).choices[0]?.message?.content||"",l=this.parseSummaryItems(o);if(l.length===0)return [];let c=s[s.length-1],u=Date.now();return l.map(d=>({schemaVersion:1,id:Yt.randomUUID(),ts:u,category:d.category,summary:ot(d.summary,Pr),sessionId:c.sessionId,runId:c.runId,files:d.files&&d.files.length>0?d.files:c.files,confidence:d.confidence,evidence:c.evidence}))}buildMemorySummaryPrompt(e){return `\u8BF7\u4ECE\u4EE5\u4E0B session \u6458\u8981\u4E2D\u63D0\u53D6\u957F\u671F\u53EF\u590D\u7528\u7684\u8BB0\u5FC6\uFF0C\u8F93\u51FA JSON \u6570\u7EC4\uFF08\u53EA\u8F93\u51FA JSON\uFF0C\u4E0D\u8981\u591A\u4F59\u6587\u672C\uFF09\u3002
3394
3394
 
3395
3395
  \u89C4\u5219\uFF1A
3396
3396
  1. category \u53EA\u80FD\u662F progress | standard | lesson | pinned
@@ -3408,5 +3408,5 @@ ${e.map(s=>{let n=Dr(s.ts),r=s.files&&s.files.length>0?` files=${s.files.join(",
3408
3408
  [
3409
3409
  {"category":"progress","summary":"\u5B8C\u6210\u4E86 X\uFF0C\u4E0B\u4E00\u6B65 Y","files":["src/app.ts"],"confidence":0.7},
3410
3410
  {"category":"lesson","summary":"\u907F\u514D\u91CD\u590D\u6267\u884C Z\uFF0C\u5BB9\u6613\u8D85\u65F6","confidence":0.5}
3411
- ]`}parseSummaryItems(e){if(!e)return [];let t=e.match(/```(?:json)?\s*([\s\S]*?)\s*```/),s=t?t[1]:e,n=s.indexOf("["),r=s.lastIndexOf("]");if(n===-1||r===-1||r<=n)return [];try{let i=JSON.parse(s.slice(n,r+1));if(!Array.isArray(i))return [];let o=["progress","standard","lesson","pinned"];return i.map(l=>({category:l.category,summary:l.summary,files:Array.isArray(l.files)?l.files.filter(Boolean):void 0,confidence:typeof l.confidence=="number"?Math.min(1,Math.max(0,l.confidence)):void 0})).filter(l=>o.includes(l.category)&&typeof l.summary=="string"&&l.summary.trim())}catch{return []}}updateRunAggregate(e){if(!e.runId)return;let t=this.runAggregates.get(e.runId);switch(t||(t={sessionId:e.sessionId,startTs:e.ts,toolCalls:0,fileChanges:0,planUpdates:0,retries:0,errors:0,files:new Set},this.runAggregates.set(e.runId,t)),e.type){case "run_start":t.startTs=e.ts,t.sessionId=e.sessionId,t.promptSummary=e.summary??e.data?.prompt;break;case "run_attempt":t.provider=e.data?.providerName??e.data?.providerId,t.model=e.data?.model;break;case "tool_call_start":t.toolCalls+=1;break;case "file_change":if(t.fileChanges+=1,e.files?.length)for(let s of e.files){if(t.files.size>=mk)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}`,pk),p=Array.from(t.files),h={schemaVersion:1,id:e.id,ts:e.ts,sessionId:t.sessionId,runId:e.runId,summary:d,files:p.length?p:void 0,evidence:{eventId:e.id},model:t.model,provider:t.provider,toolCalls:t.toolCalls||void 0,errors:t.errors||(e.type==="run_error"?1:void 0),durationMs:s,tokens:n};this.sessionSummaryQueue.push(h),m.info("SESSION_SUMMARY_QUEUED","Session summary queued",{runId:h.runId,sessionId:h.sessionId,summary:ot(h.summary,160),files:h.files,toolCalls:h.toolCalls,retries:t.retries,errors:h.errors,durationMs:h.durationMs,tokens:h.tokens}),this.enqueueSummarizer(h);}async loadSummarySnapshot(){if(this.summaryPath)try{let e=await ce__default.readFile(this.summaryPath,"utf-8"),t=JSON.parse(e);t?.items?.length&&(this.summaryItems=t.items.slice(-this.options.summaryWindow));}catch{}}async persistSummarySnapshot(){if(!this.summaryPath||!this.workspaceId||!this.summaryDirty)return;let e={schemaVersion:1,workspaceId:this.workspaceId,updatedAt:Date.now(),windowSize:this.options.summaryWindow,items:this.summaryItems},t=`${this.summaryPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.summaryPath),this.summaryDirty=false;}async loadMeta(){if(this.metaPath)try{let e=await ce__default.readFile(this.metaPath,"utf-8"),t=JSON.parse(e);if(t?.lastSeq&&(this.seq=t.lastSeq),t?.createdAt&&(this.createdAt=t.createdAt),t?.currentFile&&this.eventsDir){let s=te__default.join(this.eventsDir,t.currentFile);this.currentFile=s,this.currentDate=t.currentFile.slice(7,17),this.currentFileBytes=await this.getFileSize(s);}}catch{}}async persistMeta(){if(!this.metaPath||!this.workspaceId||!this.workspacePath||!this.workspaceName)return;let e={schemaVersion:1,workspaceId:this.workspaceId,workspacePath:this.workspacePath,workspaceName:this.workspaceName,createdAt:this.createdAt,updatedAt:Date.now(),lastSeq:this.seq,currentFile:this.currentFile?te__default.basename(this.currentFile):void 0,currentFileBytes:this.currentFileBytes,source:this.options.source,agentName:this.options.agentName},t=`${this.metaPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.metaPath);}};W();var Ho=class{id="edge";tts;constructor(){this.tts=new EdgeTTS;}async init(){}async synthesize(e,t){let s=t?.voice||"zh-CN-XiaoxiaoNeural",n=t?.speed?`${Math.round((t.speed-1)*100)}%`:"+0%",r=t?.format||"mp3",i=r==="opus"?"webm-24khz-16bit-mono-opus":"audio-24khz-48kbitrate-mono-mp3";await this.tts.synthesize(e,s,{rate:n,outputFormat:i});let o=this.tts.toBuffer(),l=this.tts.getAudioInfo();return {audio:o,format:r,durationMs:Math.round(l.estimatedDuration*1e3)}}async synthesizeStream(e,t,s){let n=s?.voice||"zh-CN-XiaoxiaoNeural",r=s?.format||"mp3",i=0;for await(let o of this.tts.synthesizeStream(e,n))o&&o.length>0&&(t(Buffer.from(o),i),i++);return {format:r,totalChunks:i}}async getVoices(){return (await this.tts.getVoicesByLanguage("zh-CN")).map(t=>({id:t.ShortName,name:t.LocalName||t.FriendlyName,locale:t.Locale,gender:t.Gender}))}destroy(){}},Jo=class{provider=null;config;summarizeFn=null;constructor(e){this.config=e;}setSummarizeFn(e){this.summarizeFn=e;}updateConfig(e){this.config={...this.config,...e};}isEnabled(){return this.config.enabled===true}async init(){if(!this.config.enabled)return;(this.config.provider||"edge")==="edge"?this.provider=new Ho:this.provider=new Ho,await this.provider.init(),m.info("TTS",`TTS service initialized with provider: ${this.provider.id}`);}async speak(e){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let t=await this.provider.synthesize(e,{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {audio:t.audio.toString("base64"),format:t.format,voiceSummary:e,durationMs:t.durationMs}}catch(t){return m.error("TTS",`TTS synthesis failed: ${t.message}`),null}}async speakStream(e,t){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let s=await this.provider.synthesizeStream(e,(n,r)=>{t(n.toString("base64"),r);},{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {format:s.format,totalChunks:s.totalChunks,voiceText:e}}catch(s){return m.error("TTS",`TTS stream synthesis failed: ${s.message}`),null}}async getVoices(){return this.provider?this.provider.getVoices():[]}destroy(){this.provider?.destroy(),this.provider=null;}};var jc=te.join(In.homedir(),".neox"),Or=te.join(jc,"server.pid");function Tk(a){Me.existsSync(jc)||Me.mkdirSync(jc,{recursive:true}),Me.writeFileSync(Or,JSON.stringify(a,null,2));}function sg(){try{Me.existsSync(Or)&&Me.unlinkSync(Or);}catch{}}function vB(){try{return Me.existsSync(Or)?JSON.parse(Me.readFileSync(Or,"utf-8")):null}catch{return null}}function _k(){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 Rk(a,e){let t=Oe(),s=Wr(),n=new rt(t),r=t.agentApprovalMode||t.approvalMode||"auto",i=Zm(r),o=(v,E)=>{let L=n.getProvider(v);if(!L)return {provider:null,llmConfig:null};let I=E||L.defaultModel||L.models?.[0]?.name;return {provider:L,llmConfig:{model:I,providerName:L.name||L.id,maxInputTokens:L.contextWindow||128e3}}},l=fo(500),c=new Lr({workspacePath:a,source:"server",agentName:"Neox Server"}),u=new Jo(t.tts??{enabled:false});t.tts?.enabled&&(u.setSummarizeFn(async(v,E,L)=>{let I=g;if(!I)return v.substring(0,E);let A=Ot.createAdapter(I.protocol,I),O=L||"claude-haiku-4-5-20251001";return (await A.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${E}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:v}],{model:O,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||v.substring(0,E)}),await u.init());let d=await un(a,s),p=Ji({workDir:a}),h=typeof p=="string"?p:"",g=n.getDefaultProvider(),f=g?.id??"",b=g?.defaultModel??g?.models?.[0]?.name??"",y={services:s,permissionManager:i,tools:d,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,systemPrompt:h},w=new zo;w.setWorkspace(a);let C=null,k=null,T=null,_=null,M=t.runMode||"single";try{C=new wn({...y,actionLog:c,agentMode:r==="dangerous"?"auto":"agent",enableFGTS:t.experimental?.enableFGTS,enablePTC:t.experimental?.enablePTC});}catch(v){m.error("SERVER","Failed to init SingleAgentRuntime",{error:v});}try{k=new xn({...y,actionLog:c});}catch(v){m.error("SERVER","Failed to init AssistantRuntime",{error:v});}try{let v=new At(void 0,"cooperate");T=new ps({...y,ccbReviewMode:v.getCCBReviewMode(),workerModels:v.getEnabledWorkerModels().map(E=>({providerId:E.providerId,model:E.model,traits:E.traits}))});}catch(v){m.error("SERVER","Failed to init CooperateRuntime",{error:v});}try{let v=async(L,I,A)=>{let O=g;if(!O)throw new Error("No provider configured for NetworkRuntime");let $=Ot.createAdapter(O.protocol,O),P=[{role:"system",content:L},{role:"user",content:I}],N=A?.model||b;if(A?.onText&&$.chatStreamed){let G="",q=$.chatStreamed(P,{model:N,maxTokens:A.maxTokens,temperature:A.temperature,signal:A.signal});for await(let oe of q)oe.type==="text"&&oe.text?(G+=oe.text,A.onText(oe.text)):oe.type==="content_block_delta"&&oe.delta?.text&&(G+=oe.delta.text,A.onText(oe.delta.text));return G}return (await $.chat(P,{model:N,maxTokens:A?.maxTokens,temperature:A?.temperature,signal:A?.signal})).choices?.[0]?.message?.content||""},E=new At(void 0,"network");_=new Rn({llmCall:v,executionCapability:{orchestrator:new $t({hostService:new Nt({platformServices:s}),resolveProvider:o}),tools:d,permissionManager:i,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,maxIterations:30},autoCreateDefaultAgents:!0,customRoles:E.getNetworkRoles?.()});}catch(v){m.error("SERVER","Failed to init NetworkRuntime",{error:v});}let F=new Set,x=new Map,R=new Map,j={async chat(v,E){F.add(v);let L=new AbortController;x.set(v,L);let I=(N,D)=>{if(m.info("SERVER",`\u{1F4E1} publishRawEvent: type=${N.type} sessionId=${v}`),e.publish({sessionId:v,type:N.type,data:N,tracker:D,timestamp:Date.now()}),N.type==="run_result"&&u.isEnabled()){let G=N.currentTurnText||N.output;G&&u.speak(G).then(q=>{q&&e.publish({sessionId:v,type:"tts_audio",data:{type:"tts_audio",audio:q.audio,audioFormat:q.format,voiceSummary:q.voiceSummary,durationMs:q.durationMs??0},timestamp:Date.now()});}).catch(q=>{m.warn("SERVER",`TTS generation failed: ${q.message}`);});}},O=N=>{e.publish({sessionId:v,type:"error",data:{type:"error",message:N.message},timestamp:Date.now()});},$={onRuntimeEvent:(N,D)=>I(N,D),onError:O},P={onRuntimeEvent:N=>I(N),onError:O};try{let N=E.mode??M,D=E.attachments?{attachments:E.attachments}:void 0;if(N==="single"&&C)await C.chat({sessionId:v,prompt:E.prompt,metadata:D,providerId:E.providerId,modelName:E.modelName},$);else if(N==="assistant"&&k)k.removeAllListeners("worker_event"),k.removeAllListeners("worker_result"),k.on("worker_event",G=>{if(G?.event){let q={...G.event,sourceLabel:G.agentId,workerRole:G.role,workerTask:G.taskSummary};I(q,G.tracker);}}),k.on("worker_result",G=>{e.publish({sessionId:v,type:"worker_result",data:{type:"worker_result",agentId:G.agentId,success:G.success,output:G.output},timestamp:Date.now()});}),await k.chat({sessionId:v,prompt:E.prompt,metadata:D});else if(N==="cooperate"&&T)await T.chat({sessionId:v,prompt:E.prompt,metadata:D},P);else if(N==="network"&&_)await _.chat({prompt:E.prompt,history:[]});else if(C)await C.chat({sessionId:v,prompt:E.prompt,metadata:D,providerId:E.providerId,modelName:E.modelName},$);else throw new Error("No runtime available")}finally{F.delete(v),x.delete(v);}},abort(v){let E=x.get(v);E&&(E.abort(),x.delete(v)),C&&C.abort(),k&&k.abort(),T&&T.abort?.();},replyPermission(v,E,L){let I=R.get(v);I&&(I.resolve(E),R.delete(v));},getActiveSessions(){return [...F]},setRunMode(v){Wo.isValidMode(v)&&(M=v,m.info("SERVER",`Run mode changed to: ${M}`));},getRunMode(){return M},setSandboxMode(v,E){lp(E);},setApprovalMode(v,E){m.info("SERVER",`Approval mode set to: ${E}`);},async compactSession(v){m.info("SERVER",`Compact session: ${v}`);},clearSession(v){l.clear(),m.info("SERVER",`Cleared session: ${v}`);},getContextHealth(v){return l.checkContextHealth?.()??null},async getSessionInfo(v){return {messageCount:l.length,messages:l.getAll()}},setCompressionMode(v,E){m.info("SERVER",`Compression mode set to: ${E}`);},getMemoryStats(v){return {length:l.length,contextHealth:l.checkContextHealth?.()??null}},clearMemory(v){l.clear();},addMemoryMessage(v,E,L){l.add({role:E,content:L});},getToolList(){return {count:d.length,names:d.map(v=>v.name)}},async reloadTools(v){let E=await un(v,s);d.length=0,d.push(...E),m.info("SERVER",`Reloaded ${d.length} tools for ${v}`);},async setWorkspace(v){let E=await un(v,s);d.length=0,d.push(...E),w.setWorkspace(v),m.info("SERVER",`Workspace switched to: ${v}`);},async startCheckpointWatching(v){return w.startMessage(v)},async stopCheckpointWatching(){await w.stopWatching();},async createCheckpoint(v,E){return w.createCheckpoint(v,E)},async rollbackToCheckpoint(v){return w.rollbackToCheckpoint(v)},async rollbackSingleFile(v){return w.rollbackSingleFile(v)},async reapplySingleFile(v){return w.reapplySingleFile(v)},async getCheckpoints(v,E){return w.getCheckpoints(v,E)},async getCheckpointStats(){return w.getCurrentStats?.()??{created:0,modified:0,deleted:0,directories:0,total:0}},async getCheckpointChanges(){return w.getChangeBuffer?.()??[]},setCheckpointEnabled(v){w.setEnabled(v);},isCheckpointEnabled(){return w.isEnabled()},async cleanupCheckpoints(){await w.cleanup?.();},async getHostStatus(){return {isRunning:F.size>0,currentTask:null,mode:M,workingDirectory:a,uptime:Math.floor(process.uptime()),memoryUsage:{tokensUsed:l.length,contextWindow:128e3,pressure:l.length/128e3}}},async getHostAgents(){return [{id:"main",role:"main",status:F.size>0?"running":"idle"}]},async getHostActivity(v=10){return []},async getHostSession(){return {messageCount:l.length,tokensUsed:0}},async getHostSystem(){let v=null,E="unknown";try{let{execSync:L}=await import('child_process');try{v=L("git rev-parse --abbrev-ref HEAD",{cwd:a,encoding:"utf-8",timeout:5e3}).trim();}catch{}try{E=L("git status --porcelain",{cwd:a,encoding:"utf-8",timeout:5e3}).trim().length===0?"clean":"dirty";}catch{}}catch{}return {platform:process.platform,arch:process.arch,cwd:a,gitBranch:v,gitStatus:E,nodeVersion:process.version}},async hostInterrupt(v){for(let[L,I]of x)I.abort();C&&C.abort(),k&&k.abort(),T&&T.abort?.();let E=F.size>0;return F.clear(),x.clear(),{interrupted:E}},async hostSendCommand(v,E){let L=`cmd-${Date.now()}`,I={prompt:v};return j.chat(L,I).catch(A=>{m.error("SERVER",`hostSendCommand failed: ${A.message}`);}),{queued:true,sessionId:L}},setTTSEnabled(v){let E=u.isEnabled();u.updateConfig({enabled:v,provider:"edge"}),v&&!E&&(u.summarizeFn||u.setSummarizeFn(async(L,I,A)=>{let O=g;if(!O)return L.substring(0,I);let $=Ot.createAdapter(O.protocol,O),P=A||"claude-haiku-4-5-20251001";return (await $.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${I}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:L}],{model:P,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||L.substring(0,I)}),u.init().catch(L=>{m.error("SERVER",`TTS init failed: ${L.message}`);})),m.info("SERVER",`TTS ${v?"enabled":"disabled"}`);},isTTSEnabled(){return u.isEnabled()},getTTSConfig(){return t.tts??{enabled:false}},updateTTSConfig(v){let E=u.isEnabled();u.updateConfig(v),v.enabled&&!E&&u.init().catch(L=>{m.error("SERVER",`TTS init failed: ${L.message}`);});}};return j}async function Ak(){let{port:a,workDir:e,daemon:t}=_k(),s=Oe(),n=s.remote??{};m.info("SERVER",`Starting Neox Server on port ${a}, workDir: ${e}`);let r=new Br,i=new Ns,o=await Rk(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}=Jc(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");Tk({pid:process.pid,port:a,workDir:e,startedAt:Date.now(),daemon:t});let h=()=>{m.info("SERVER","Shutting down..."),ht.stopWatch(),u.stopAll().catch(()=>{}),sg(),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});});}Ak().catch(a=>{m.error("SERVER","Failed to start server",{error:a}),sg(),process.exit(1);});
3412
- export{vB as readPidFile};
3411
+ ]`}parseSummaryItems(e){if(!e)return [];let t=e.match(/```(?:json)?\s*([\s\S]*?)\s*```/),s=t?t[1]:e,n=s.indexOf("["),r=s.lastIndexOf("]");if(n===-1||r===-1||r<=n)return [];try{let i=JSON.parse(s.slice(n,r+1));if(!Array.isArray(i))return [];let o=["progress","standard","lesson","pinned"];return i.map(l=>({category:l.category,summary:l.summary,files:Array.isArray(l.files)?l.files.filter(Boolean):void 0,confidence:typeof l.confidence=="number"?Math.min(1,Math.max(0,l.confidence)):void 0})).filter(l=>o.includes(l.category)&&typeof l.summary=="string"&&l.summary.trim())}catch{return []}}updateRunAggregate(e){if(!e.runId)return;let t=this.runAggregates.get(e.runId);switch(t||(t={sessionId:e.sessionId,startTs:e.ts,toolCalls:0,fileChanges:0,planUpdates:0,retries:0,errors:0,files:new Set},this.runAggregates.set(e.runId,t)),e.type){case "run_start":t.startTs=e.ts,t.sessionId=e.sessionId,t.promptSummary=e.summary??e.data?.prompt;break;case "run_attempt":t.provider=e.data?.providerName??e.data?.providerId,t.model=e.data?.model;break;case "tool_call_start":t.toolCalls+=1;break;case "file_change":if(t.fileChanges+=1,e.files?.length)for(let s of e.files){if(t.files.size>=gk)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}`,mk),p=Array.from(t.files),h={schemaVersion:1,id:e.id,ts:e.ts,sessionId:t.sessionId,runId:e.runId,summary:d,files:p.length?p:void 0,evidence:{eventId:e.id},model:t.model,provider:t.provider,toolCalls:t.toolCalls||void 0,errors:t.errors||(e.type==="run_error"?1:void 0),durationMs:s,tokens:n};this.sessionSummaryQueue.push(h),m.info("SESSION_SUMMARY_QUEUED","Session summary queued",{runId:h.runId,sessionId:h.sessionId,summary:ot(h.summary,160),files:h.files,toolCalls:h.toolCalls,retries:t.retries,errors:h.errors,durationMs:h.durationMs,tokens:h.tokens}),this.enqueueSummarizer(h);}async loadSummarySnapshot(){if(this.summaryPath)try{let e=await ce__default.readFile(this.summaryPath,"utf-8"),t=JSON.parse(e);t?.items?.length&&(this.summaryItems=t.items.slice(-this.options.summaryWindow));}catch{}}async persistSummarySnapshot(){if(!this.summaryPath||!this.workspaceId||!this.summaryDirty)return;let e={schemaVersion:1,workspaceId:this.workspaceId,updatedAt:Date.now(),windowSize:this.options.summaryWindow,items:this.summaryItems},t=`${this.summaryPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.summaryPath),this.summaryDirty=false;}async loadMeta(){if(this.metaPath)try{let e=await ce__default.readFile(this.metaPath,"utf-8"),t=JSON.parse(e);if(t?.lastSeq&&(this.seq=t.lastSeq),t?.createdAt&&(this.createdAt=t.createdAt),t?.currentFile&&this.eventsDir){let s=te__default.join(this.eventsDir,t.currentFile);this.currentFile=s,this.currentDate=t.currentFile.slice(7,17),this.currentFileBytes=await this.getFileSize(s);}}catch{}}async persistMeta(){if(!this.metaPath||!this.workspaceId||!this.workspacePath||!this.workspaceName)return;let e={schemaVersion:1,workspaceId:this.workspaceId,workspacePath:this.workspacePath,workspaceName:this.workspaceName,createdAt:this.createdAt,updatedAt:Date.now(),lastSeq:this.seq,currentFile:this.currentFile?te__default.basename(this.currentFile):void 0,currentFileBytes:this.currentFileBytes,source:this.options.source,agentName:this.options.agentName},t=`${this.metaPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.metaPath);}};W();var Ho=class{id="edge";tts;constructor(){this.tts=new EdgeTTS;}async init(){}async synthesize(e,t){let s=t?.voice||"zh-CN-XiaoxiaoNeural",n=t?.speed?`${Math.round((t.speed-1)*100)}%`:"+0%",r=t?.format||"mp3",i=r==="opus"?"webm-24khz-16bit-mono-opus":"audio-24khz-48kbitrate-mono-mp3";await this.tts.synthesize(e,s,{rate:n,outputFormat:i});let o=this.tts.toBuffer(),l=this.tts.getAudioInfo();return {audio:o,format:r,durationMs:Math.round(l.estimatedDuration*1e3)}}async synthesizeStream(e,t,s){let n=s?.voice||"zh-CN-XiaoxiaoNeural",r=s?.format||"mp3",i=0;for await(let o of this.tts.synthesizeStream(e,n))o&&o.length>0&&(t(Buffer.from(o),i),i++);return {format:r,totalChunks:i}}async getVoices(){return (await this.tts.getVoicesByLanguage("zh-CN")).map(t=>({id:t.ShortName,name:t.LocalName||t.FriendlyName,locale:t.Locale,gender:t.Gender}))}destroy(){}},Jo=class{provider=null;config;summarizeFn=null;constructor(e){this.config=e;}setSummarizeFn(e){this.summarizeFn=e;}updateConfig(e){this.config={...this.config,...e};}isEnabled(){return this.config.enabled===true}async init(){if(!this.config.enabled)return;(this.config.provider||"edge")==="edge"?this.provider=new Ho:this.provider=new Ho,await this.provider.init(),m.info("TTS",`TTS service initialized with provider: ${this.provider.id}`);}async speak(e){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let t=await this.provider.synthesize(e,{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {audio:t.audio.toString("base64"),format:t.format,voiceSummary:e,durationMs:t.durationMs}}catch(t){return m.error("TTS",`TTS synthesis failed: ${t.message}`),null}}async speakStream(e,t){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let s=await this.provider.synthesizeStream(e,(n,r)=>{t(n.toString("base64"),r);},{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {format:s.format,totalChunks:s.totalChunks,voiceText:e}}catch(s){return m.error("TTS",`TTS stream synthesis failed: ${s.message}`),null}}async getVoices(){return this.provider?this.provider.getVoices():[]}destroy(){this.provider?.destroy(),this.provider=null;}};var jc=te.join(In.homedir(),".neox"),Or=te.join(jc,"server.pid");function _k(a){Me.existsSync(jc)||Me.mkdirSync(jc,{recursive:true}),Me.writeFileSync(Or,JSON.stringify(a,null,2));}function sg(){try{Me.existsSync(Or)&&Me.unlinkSync(Or);}catch{}}function CB(){try{return Me.existsSync(Or)?JSON.parse(Me.readFileSync(Or,"utf-8")):null}catch{return null}}function Rk(){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 Ak(a,e){let t=Oe(),s=Wr(),n=new rt(t),r=t.agentApprovalMode||t.approvalMode||"auto",i=Zm(r),o=(v,E)=>{let L=n.getProvider(v);if(!L)return {provider:null,llmConfig:null};let I=E||L.defaultModel||L.models?.[0]?.name;return {provider:L,llmConfig:{model:I,providerName:L.name||L.id,maxInputTokens:L.contextWindow||128e3}}},l=fo(500),c=new Lr({workspacePath:a,source:"server",agentName:"Neox Server"}),u=new Jo(t.tts??{enabled:false});t.tts?.enabled&&(u.setSummarizeFn(async(v,E,L)=>{let I=g;if(!I)return v.substring(0,E);let A=Ot.createAdapter(I.protocol,I),O=L||"claude-haiku-4-5-20251001";return (await A.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${E}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:v}],{model:O,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||v.substring(0,E)}),await u.init());let d=await un(a,s),p=Ji({workDir:a}),h=typeof p=="string"?p:"",g=n.getDefaultProvider(),f=g?.id??"",b=g?.defaultModel??g?.models?.[0]?.name??"",y={services:s,permissionManager:i,tools:d,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,systemPrompt:h},w=new zo;w.setWorkspace(a);let C=null,k=null,T=null,_=null,M=t.runMode||"single";try{C=new wn({...y,actionLog:c,agentMode:r==="dangerous"?"auto":"agent",enableFGTS:t.experimental?.enableFGTS,enablePTC:t.experimental?.enablePTC});}catch(v){m.error("SERVER","Failed to init SingleAgentRuntime",{error:v});}try{k=new xn({...y,actionLog:c});}catch(v){m.error("SERVER","Failed to init AssistantRuntime",{error:v});}try{let v=new At(void 0,"cooperate");T=new ps({...y,ccbReviewMode:v.getCCBReviewMode(),workerModels:v.getEnabledWorkerModels().map(E=>({providerId:E.providerId,model:E.model,traits:E.traits}))});}catch(v){m.error("SERVER","Failed to init CooperateRuntime",{error:v});}try{let v=async(L,I,A)=>{let O=g;if(!O)throw new Error("No provider configured for NetworkRuntime");let $=Ot.createAdapter(O.protocol,O),P=[{role:"system",content:L},{role:"user",content:I}],N=A?.model||b;if(A?.onText&&$.chatStreamed){let G="",q=$.chatStreamed(P,{model:N,maxTokens:A.maxTokens,temperature:A.temperature,signal:A.signal});for await(let oe of q)oe.type==="text"&&oe.text?(G+=oe.text,A.onText(oe.text)):oe.type==="content_block_delta"&&oe.delta?.text&&(G+=oe.delta.text,A.onText(oe.delta.text));return G}return (await $.chat(P,{model:N,maxTokens:A?.maxTokens,temperature:A?.temperature,signal:A?.signal})).choices?.[0]?.message?.content||""},E=new At(void 0,"network");_=new Rn({llmCall:v,executionCapability:{orchestrator:new $t({hostService:new Nt({platformServices:s}),resolveProvider:o}),tools:d,permissionManager:i,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,maxIterations:30},autoCreateDefaultAgents:!0,customRoles:E.getNetworkRoles?.()});}catch(v){m.error("SERVER","Failed to init NetworkRuntime",{error:v});}let F=new Set,x=new Map,R=new Map,j={async chat(v,E){F.add(v);let L=new AbortController;x.set(v,L);let I=(N,D)=>{if(m.info("SERVER",`\u{1F4E1} publishRawEvent: type=${N.type} sessionId=${v}`),e.publish({sessionId:v,type:N.type,data:N,tracker:D,timestamp:Date.now()}),N.type==="run_result"&&u.isEnabled()){let G=N.currentTurnText||N.output;G&&u.speak(G).then(q=>{q&&e.publish({sessionId:v,type:"tts_audio",data:{type:"tts_audio",audio:q.audio,audioFormat:q.format,voiceSummary:q.voiceSummary,durationMs:q.durationMs??0},timestamp:Date.now()});}).catch(q=>{m.warn("SERVER",`TTS generation failed: ${q.message}`);});}},O=N=>{e.publish({sessionId:v,type:"error",data:{type:"error",message:N.message},timestamp:Date.now()});},$={onRuntimeEvent:(N,D)=>I(N,D),onError:O},P={onRuntimeEvent:N=>I(N),onError:O};try{let N=E.mode??M,D=E.attachments?{attachments:E.attachments}:void 0;if(N==="single"&&C)await C.chat({sessionId:v,prompt:E.prompt,metadata:D,providerId:E.providerId,modelName:E.modelName},$);else if(N==="assistant"&&k)k.removeAllListeners("worker_event"),k.removeAllListeners("worker_result"),k.on("worker_event",G=>{if(G?.event){let q={...G.event,sourceLabel:G.agentId,workerRole:G.role,workerTask:G.taskSummary};I(q,G.tracker);}}),k.on("worker_result",G=>{e.publish({sessionId:v,type:"worker_result",data:{type:"worker_result",agentId:G.agentId,success:G.success,output:G.output},timestamp:Date.now()});}),await k.chat({sessionId:v,prompt:E.prompt,metadata:D});else if(N==="cooperate"&&T)await T.chat({sessionId:v,prompt:E.prompt,metadata:D},P);else if(N==="network"&&_)await _.chat({prompt:E.prompt,history:[]});else if(C)await C.chat({sessionId:v,prompt:E.prompt,metadata:D,providerId:E.providerId,modelName:E.modelName},$);else throw new Error("No runtime available")}finally{F.delete(v),x.delete(v);}},abort(v){let E=x.get(v);E&&(E.abort(),x.delete(v)),C&&C.abort(),k&&k.abort(),T&&T.abort?.();},replyPermission(v,E,L){let I=R.get(v);I&&(I.resolve(E),R.delete(v));},getActiveSessions(){return [...F]},setRunMode(v){Wo.isValidMode(v)&&(M=v,m.info("SERVER",`Run mode changed to: ${M}`));},getRunMode(){return M},setSandboxMode(v,E){lp(E);},setApprovalMode(v,E){m.info("SERVER",`Approval mode set to: ${E}`);},async compactSession(v){m.info("SERVER",`Compact session: ${v}`);},clearSession(v){l.clear(),m.info("SERVER",`Cleared session: ${v}`);},getContextHealth(v){return l.checkContextHealth?.()??null},async getSessionInfo(v){return {messageCount:l.length,messages:l.getAll()}},setCompressionMode(v,E){m.info("SERVER",`Compression mode set to: ${E}`);},getMemoryStats(v){return {length:l.length,contextHealth:l.checkContextHealth?.()??null}},clearMemory(v){l.clear();},addMemoryMessage(v,E,L){l.add({role:E,content:L});},getToolList(){return {count:d.length,names:d.map(v=>v.name)}},async reloadTools(v){let E=await un(v,s);d.length=0,d.push(...E),m.info("SERVER",`Reloaded ${d.length} tools for ${v}`);},async setWorkspace(v){let E=await un(v,s);d.length=0,d.push(...E),w.setWorkspace(v),m.info("SERVER",`Workspace switched to: ${v}`);},async startCheckpointWatching(v){return w.startMessage(v)},async stopCheckpointWatching(){await w.stopWatching();},async createCheckpoint(v,E){return w.createCheckpoint(v,E)},async rollbackToCheckpoint(v){return w.rollbackToCheckpoint(v)},async rollbackSingleFile(v){return w.rollbackSingleFile(v)},async reapplySingleFile(v){return w.reapplySingleFile(v)},async getCheckpoints(v,E){return w.getCheckpoints(v,E)},async getCheckpointStats(){return w.getCurrentStats?.()??{created:0,modified:0,deleted:0,directories:0,total:0}},async getCheckpointChanges(){return w.getChangeBuffer?.()??[]},setCheckpointEnabled(v){w.setEnabled(v);},isCheckpointEnabled(){return w.isEnabled()},async cleanupCheckpoints(){await w.cleanup?.();},async getHostStatus(){return {isRunning:F.size>0,currentTask:null,mode:M,workingDirectory:a,uptime:Math.floor(process.uptime()),memoryUsage:{tokensUsed:l.length,contextWindow:128e3,pressure:l.length/128e3}}},async getHostAgents(){return [{id:"main",role:"main",status:F.size>0?"running":"idle"}]},async getHostActivity(v=10){return []},async getHostSession(){return {messageCount:l.length,tokensUsed:0}},async getHostSystem(){let v=null,E="unknown";try{let{execSync:L}=await import('child_process');try{v=L("git rev-parse --abbrev-ref HEAD",{cwd:a,encoding:"utf-8",timeout:5e3}).trim();}catch{}try{E=L("git status --porcelain",{cwd:a,encoding:"utf-8",timeout:5e3}).trim().length===0?"clean":"dirty";}catch{}}catch{}return {platform:process.platform,arch:process.arch,cwd:a,gitBranch:v,gitStatus:E,nodeVersion:process.version}},async hostInterrupt(v){for(let[L,I]of x)I.abort();C&&C.abort(),k&&k.abort(),T&&T.abort?.();let E=F.size>0;return F.clear(),x.clear(),{interrupted:E}},async hostSendCommand(v,E){let L=`cmd-${Date.now()}`,I={prompt:v};return j.chat(L,I).catch(A=>{m.error("SERVER",`hostSendCommand failed: ${A.message}`);}),{queued:true,sessionId:L}},setTTSEnabled(v){let E=u.isEnabled();u.updateConfig({enabled:v,provider:"edge"}),v&&!E&&(u.summarizeFn||u.setSummarizeFn(async(L,I,A)=>{let O=g;if(!O)return L.substring(0,I);let $=Ot.createAdapter(O.protocol,O),P=A||"claude-haiku-4-5-20251001";return (await $.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${I}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:L}],{model:P,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||L.substring(0,I)}),u.init().catch(L=>{m.error("SERVER",`TTS init failed: ${L.message}`);})),m.info("SERVER",`TTS ${v?"enabled":"disabled"}`);},isTTSEnabled(){return u.isEnabled()},getTTSConfig(){return t.tts??{enabled:false}},updateTTSConfig(v){let E=u.isEnabled();u.updateConfig(v),v.enabled&&!E&&u.init().catch(L=>{m.error("SERVER",`TTS init failed: ${L.message}`);});}};return j}async function Ek(){let{port:a,workDir:e,daemon:t}=Rk(),s=Oe(),n=s.remote??{};m.info("SERVER",`Starting Neox Server on port ${a}, workDir: ${e}`);let r=new Br,i=new Ns,o=await Ak(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}=Jc(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");_k({pid:process.pid,port:a,workDir:e,startedAt:Date.now(),daemon:t});let h=()=>{m.info("SERVER","Shutting down..."),ht.stopWatch(),u.stopAll().catch(()=>{}),sg(),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});});}Ek().catch(a=>{m.error("SERVER","Failed to start server",{error:a}),sg(),process.exit(1);});
3412
+ export{CB as readPidFile};