@mk-co/neox-cli 2.0.11 → 2.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/main.js +30 -30
- package/package.json +1 -1
package/dist/cli/main.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as Je from'fs';import Je__default,{realpathSync,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,readFileSync,createReadStream,existsSync,mkdirSync,writeFileSync}from'fs';import*as he from'path';import he__default,{dirname,join,win32,posix}from'path';import*as gi from'os';import gi__default,{homedir,tmpdir,platform}from'os';import {spawn,fork,spawnSync,execSync}from'child_process';import {EventEmitter}from'events';import {execa,execaSync}from'execa';import*as Se from'fs/promises';import Se__default,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import {fileURLToPath,URL as URL$1}from'url';import Ie from'chalk';import {performance as performance$1}from'perf_hooks';import*as ip from'readline';import ip__default from'readline';import Rc from'prompts';import I,{createContext,forwardRef,useContext,useState,useEffect,useMemo,useRef,PureComponent,useLayoutEffect}from'react';import Rh,{Stream}from'stream';import Qt,{cwd}from'process';import {throttle}from'es-toolkit/compat';import wn from'ansi-escapes';import ns from'is-in-ci';import Hx from'auto-bind';import {onExit}from'signal-exit';import qx from'patch-console';import {NoEventPriority,DefaultEventPriority,LegacyRoot}from'react-reconciler/constants.js';import ye from'yoga-layout';import IC from'wrap-ansi';import GC from'react-reconciler';import SC from'widest-line';import sr from'slice-ansi';import Wi from'string-width';import {styledCharsFromTokens,tokenize,styledCharsToString}from'@alcalzone/ansi-tokenize';import Zi from'cli-cursor';import gg from'stack-utils';import {Buffer as Buffer$1}from'buffer';import ET from'ajv';import er,{randomUUID,createHash,randomBytes}from'crypto';import {StringDecoder}from'string_decoder';import iy from'fast-glob';import zk from'puppeteer-core';import*as Hf from'net';import {Marked}from'marked';import {markedTerminal}from'marked-terminal';import {Box,Text}from'ink';import vl from'ink-spinner';import CI from'axios';import wA from'http';var fC=Object.create;var ji=Object.defineProperty;var yC=Object.getOwnPropertyDescriptor;var bC=Object.getOwnPropertyNames;var vC=Object.getPrototypeOf,CC=Object.prototype.hasOwnProperty;var Mm=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var Qe=(s,e)=>()=>(s&&(e=s(s=0)),e);var lo=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Vr=(s,e)=>{for(var t in e)ji(s,t,{get:e[t],enumerable:true});},Pm=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of bC(e))!CC.call(s,r)&&r!==t&&ji(s,r,{get:()=>e[r],enumerable:!(n=yC(e,r))||n.enumerable});return s};var Rm=(s,e,t)=>(t=s!=null?fC(vC(s)):{},Pm(ji(t,"default",{value:s,enumerable:true}),s)),Nc=s=>Pm(ji({},"__esModule",{value:true}),s);var Gi={};Vr(Gi,{cliHealthMonitor:()=>Ht,cliLogger:()=>p,debugLog:()=>
|
|
2
|
+
import*as Je from'fs';import Je__default,{realpathSync,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,readFileSync,createReadStream,existsSync,mkdirSync,writeFileSync}from'fs';import*as he from'path';import he__default,{dirname,join,win32,posix}from'path';import*as gi from'os';import gi__default,{homedir,tmpdir,platform}from'os';import {spawn,fork,spawnSync,execSync}from'child_process';import {EventEmitter}from'events';import {execa,execaSync}from'execa';import*as Se from'fs/promises';import Se__default,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import {fileURLToPath,URL as URL$1}from'url';import Ie from'chalk';import {performance as performance$1}from'perf_hooks';import*as ip from'readline';import ip__default from'readline';import Rc from'prompts';import I,{createContext,forwardRef,useContext,useState,useEffect,useMemo,useRef,PureComponent,useLayoutEffect}from'react';import Rh,{Stream}from'stream';import Qt,{cwd}from'process';import {throttle}from'es-toolkit/compat';import wn from'ansi-escapes';import ns from'is-in-ci';import Hx from'auto-bind';import {onExit}from'signal-exit';import qx from'patch-console';import {NoEventPriority,DefaultEventPriority,LegacyRoot}from'react-reconciler/constants.js';import ye from'yoga-layout';import IC from'wrap-ansi';import GC from'react-reconciler';import SC from'widest-line';import sr from'slice-ansi';import Wi from'string-width';import {styledCharsFromTokens,tokenize,styledCharsToString}from'@alcalzone/ansi-tokenize';import Zi from'cli-cursor';import gg from'stack-utils';import {Buffer as Buffer$1}from'buffer';import ET from'ajv';import er,{randomUUID,createHash,randomBytes}from'crypto';import {StringDecoder}from'string_decoder';import iy from'fast-glob';import zk from'puppeteer-core';import*as Hf from'net';import {Marked}from'marked';import {markedTerminal}from'marked-terminal';import {Box,Text}from'ink';import vl from'ink-spinner';import CI from'axios';import wA from'http';var fC=Object.create;var ji=Object.defineProperty;var yC=Object.getOwnPropertyDescriptor;var bC=Object.getOwnPropertyNames;var vC=Object.getPrototypeOf,CC=Object.prototype.hasOwnProperty;var Mm=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var Qe=(s,e)=>()=>(s&&(e=s(s=0)),e);var lo=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Vr=(s,e)=>{for(var t in e)ji(s,t,{get:e[t],enumerable:true});},Pm=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of bC(e))!CC.call(s,r)&&r!==t&&ji(s,r,{get:()=>e[r],enumerable:!(n=yC(e,r))||n.enumerable});return s};var Rm=(s,e,t)=>(t=s!=null?fC(vC(s)):{},Pm(ji(t,"default",{value:s,enumerable:true}),s)),Nc=s=>Pm(ji({},"__esModule",{value:true}),s);var Gi={};Vr(Gi,{cliHealthMonitor:()=>Ht,cliLogger:()=>p,debugLog:()=>oe,generateCurlCommand:()=>Fn,installCrashHandler:()=>Fc,logCurlCommand:()=>Bc});function Fn(s,e,t,n=true){let r=["curl -X POST \\"];r.push(` '${s}' \\`);for(let[i,a]of Object.entries(e)){let l=a;if(n){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)}`);}r.push(` -H '${i}: ${l}' \\`);}let o=JSON.stringify(t);return r.push(` -d '${TC(o)}'`),r.join(`
|
|
3
3
|
`)}function TC(s){return s.replace(/'/g,"'\\''")}function Bc(s,e,t){if(process.env.CLI_DEBUG!=="1")return;let n=Fn(s,e,t);p.info("CURL","=== LLM Request CURL Command ==="),p.info("CURL",n),p.info("CURL","=== End CURL Command ==="),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
|
|
4
4
|
[CURL] === LLM Request CURL Command ===`),console.log(n),console.log(`[CURL] === End CURL Command ===
|
|
5
|
-
`));}function
|
|
5
|
+
`));}function oe(s,e,t){if(process.env.CLI_DEBUG==="1"&&(p.debug(s,e,t),process.env.CLI_DEBUG_CONSOLE==="1")){let n=s?`[${s}]`:"";t!==void 0?console.log(n,e,t):console.log(n,e);}}function Fc(){process.on("uncaughtException",s=>{p.error("CRASH","Uncaught Exception",{name:s.name,message:s.message,stack:s.stack}),setTimeout(()=>process.exit(1),100);}),process.on("unhandledRejection",s=>{p.error("CRASH","Unhandled Rejection",{reason:s instanceof Error?{name:s.name,message:s.message,stack:s.stack}:s});});try{process.on("SIGTTIN","ignore"),process.on("SIGTTOU","ignore"),p.info("SIGNAL","TTY control signals (SIGTTIN/SIGTTOU) initialized in crashHandler");}catch{}process.on("exit",()=>{p.close();});}var Oc,p,$c,Ht,Z=Qe(()=>{Oc=class{logDir;enabled=true;initialized=false;writeStream=null;currentLogFile=null;backpressured=false;constructor(){this.logDir=he__default.join(gi__default.homedir(),".neox","logs");}init(){if(!this.initialized)try{Je__default.existsSync(this.logDir)||Je__default.mkdirSync(this.logDir,{recursive:!0}),this.initialized=!0;}catch{this.enabled=false;}}getLogFilePath(){let e=new Date().toISOString().split("T")[0];return he__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=Je__default.createWriteStream(e,{flags:"a"}),this.currentLogFile=e),this.writeStream}formatLocalTime(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return `${t}-${n}-${r} ${o}:${i}:${a}.${l}`}formatMessage(e,t,n,r){let o=this.formatLocalTime(),i=e.toUpperCase().padEnd(5),a=t?`[${t}]`:"",l=`${o} ${i} ${a} ${n}`;if(r!==void 0)try{let c=this.safeStringify(r);l+=` ${c}`;}catch{l+=" [Serialization Error]";}return l+`
|
|
6
6
|
`}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(n,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return "[Circular]";t.add(r);}return n==="parser"||n==="socket"||n==="_httpMessage"||n==="req"||n==="res"?"[Omitted]":r&&r.type==="Buffer"&&Array.isArray(r.data)?"[Buffer]":typeof r=="function"?"[Function]":r instanceof Error?{name:r.name,message:r.message,stack:r.stack}:r})}write(e,t,n,r){if(!this.enabled)return;let o=this.ensureStream();if(!o||this.backpressured&&e==="debug")return;let i=this.formatMessage(e,t,n,r);!o.write(i)&&!this.backpressured&&(this.backpressured=true,o.once("drain",()=>{this.backpressured=false;}));}debug(e,t,n){this.write("debug",e,t,n);}info(e,t,n){this.write("info",e,t,n);}warn(e,t,n){this.write("warn",e,t,n);}error(e,t,n){this.write("error",e,t,n);}log(e,...t){let n=t.map(r=>{if(typeof r=="string")return r;try{return this.safeStringify(r)}catch{return String(r)}}).join(" ");this.write("info",e,n);}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);}},p=new Oc;$c=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){p.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,p.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,p.info("HEALTH","Health monitor stopped"));}stdinDestroyedCount=0;checkHealth(){let e=Date.now(),t=e-this.lastHeartbeat;this.lastHeartbeat=e,this.heartbeatCount++;let n=this.getStdinState();if(n.isPaused?this.stdinPausedCount++:this.stdinPausedCount=0,n.destroyed){if(this.stdinDestroyedCount++,this.stdinDestroyedCount>=3){p.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;p.debug("HEALTH",`[pid=${this.pid}] Heartbeat #${this.heartbeatCount}`,{elapsed:`${t}ms`,stdin:n,stdinPausedCount:this.stdinPausedCount}),this.stdinPausedCount>=3&&p.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F stdin has been paused for ${this.stdinPausedCount} consecutive checks!`,{stdin:n}),t>1e4&&p.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();p.debug("STDIN",`[${e}] stdin state`,t);}logInkState(e,t){process.env.CLI_DEBUG==="1"&&p.debug("INK",`[${e}]`,t);}},Ht=new $c;});var jm={};Vr(jm,{default:()=>jC});var jC,Gm=Qe(()=>{jC={};});var Jm=lo((aR,qC)=>{qC.exports={single:{topLeft:"\u250C",top:"\u2500",topRight:"\u2510",right:"\u2502",bottomRight:"\u2518",bottom:"\u2500",bottomLeft:"\u2514",left:"\u2502"},double:{topLeft:"\u2554",top:"\u2550",topRight:"\u2557",right:"\u2551",bottomRight:"\u255D",bottom:"\u2550",bottomLeft:"\u255A",left:"\u2551"},round:{topLeft:"\u256D",top:"\u2500",topRight:"\u256E",right:"\u2502",bottomRight:"\u256F",bottom:"\u2500",bottomLeft:"\u2570",left:"\u2502"},bold:{topLeft:"\u250F",top:"\u2501",topRight:"\u2513",right:"\u2503",bottomRight:"\u251B",bottom:"\u2501",bottomLeft:"\u2517",left:"\u2503"},singleDouble:{topLeft:"\u2553",top:"\u2500",topRight:"\u2556",right:"\u2551",bottomRight:"\u255C",bottom:"\u2500",bottomLeft:"\u2559",left:"\u2551"},doubleSingle:{topLeft:"\u2552",top:"\u2550",topRight:"\u2555",right:"\u2502",bottomRight:"\u255B",bottom:"\u2550",bottomLeft:"\u2558",left:"\u2502"},classic:{topLeft:"+",top:"-",topRight:"+",right:"|",bottomRight:"+",bottom:"-",bottomLeft:"+",left:"|"},arrow:{topLeft:"\u2198",top:"\u2193",topRight:"\u2199",right:"\u2190",bottomRight:"\u2196",bottom:"\u2191",bottomLeft:"\u2197",left:"\u2192"}};});var Ym=lo((lR,Qc)=>{var Vm=Jm();Qc.exports=Vm;Qc.exports.default=Vm;});var Tg={};Vr(Tg,{hasClipboardImage:()=>bg,imageFileToBase64:()=>Ox,imageFileToBase64Data:()=>xg,pasteImageAsBase64:()=>cu,saveClipboardImage:()=>vg,tryPasteClipboardImage:()=>Cg});function Ax(){if(process.platform!=="darwin")return null;if(yg)return au;yg=true;let s=he.join(gi.tmpdir(),"neox-clipboard-tool");if(Je.existsSync(s))return au=s,s;let e=`
|
|
7
7
|
import Cocoa
|
|
8
8
|
let pb = NSPasteboard.general
|
|
@@ -190,14 +190,14 @@ $ npm install --save-dev react-devtools-core
|
|
|
190
190
|
`||n.length===0){s.write(wn.eraseLines(l)+a),n=a,t=c;return}let m=[];u<l?m.push(wn.eraseLines(l-u+1),wn.cursorUp(d)):m.push(wn.cursorUp(l-1));for(let g=0;g<d;g++){if(c[g]===t[g]){m.push(wn.cursorNextLine);continue}m.push(wn.cursorTo(0)+c[g]+wn.eraseEndLine+`
|
|
191
191
|
`);}s.write(m.join("")),n=a,t=c;};return o.clear=()=>{s.write(wn.eraseLines(t.length)),n="",t=[];},o.done=()=>{n="",t=[],e||(Zi.show(),r=false);},o.sync=i=>{let a=i+`
|
|
192
192
|
`;n=a,t=a.split(`
|
|
193
|
-
`);},o},cx=(s,{showCursor:e=false,incremental:t=false}={})=>t?lx(s,{showCursor:e}):ax(s,{showCursor:e}),ux={create:cx},rg=ux;var dx=new WeakMap,Qr=dx;var sg=createContext({exit(){}});sg.displayName="InternalAppContext";var ea=sg;var og=createContext({stdin:Qt.stdin,internal_eventEmitter:new EventEmitter,setRawMode(){},isRawModeSupported:false,internal_exitOnCtrlC:true});og.displayName="InternalStdinContext";var Zr=og;var ig=createContext({stdout:Qt.stdout,write(){},columns:Qt.stdout.columns||80,rows:Qt.stdout.rows||24});ig.displayName="InternalStdoutContext";var mo=ig;var ag=createContext({stderr:Qt.stderr,write(){}});ag.displayName="InternalStderrContext";var tu=ag;var lg=createContext({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});lg.displayName="InternalFocusContext";var ta=lg;Z();var ra=class{stdin;stdinListener=null;healthCheckInterval=null;constructor(e){this.stdin=e;}enablePermanent(e){this.stdinListener=e;try{this.stdin.setRawMode(!0),this.stdin.setEncoding("utf8");}catch(t){throw
|
|
193
|
+
`);},o},cx=(s,{showCursor:e=false,incremental:t=false}={})=>t?lx(s,{showCursor:e}):ax(s,{showCursor:e}),ux={create:cx},rg=ux;var dx=new WeakMap,Qr=dx;var sg=createContext({exit(){}});sg.displayName="InternalAppContext";var ea=sg;var og=createContext({stdin:Qt.stdin,internal_eventEmitter:new EventEmitter,setRawMode(){},isRawModeSupported:false,internal_exitOnCtrlC:true});og.displayName="InternalStdinContext";var Zr=og;var ig=createContext({stdout:Qt.stdout,write(){},columns:Qt.stdout.columns||80,rows:Qt.stdout.rows||24});ig.displayName="InternalStdoutContext";var mo=ig;var ag=createContext({stderr:Qt.stderr,write(){}});ag.displayName="InternalStderrContext";var tu=ag;var lg=createContext({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});lg.displayName="InternalFocusContext";var ta=lg;Z();var ra=class{stdin;stdinListener=null;healthCheckInterval=null;constructor(e){this.stdin=e;}enablePermanent(e){this.stdinListener=e;try{this.stdin.setRawMode(!0),this.stdin.setEncoding("utf8");}catch(t){throw oe("INPUT_MANAGER",`\u274C setRawMode failed: ${t}`),t}this.stdin.on("data",this.handleStdinData),this.stdin.isPaused?.()&&(this.stdin.resume(),oe("INPUT_MANAGER","\u{1F504} Stdin was paused, resumed")),this.healthCheckInterval=setInterval(()=>{this.stdin.isPaused?.()&&(oe("INPUT_MANAGER","\u26A0\uFE0F Stdin was paused, resuming..."),this.stdin.resume());},100),oe("INPUT_MANAGER","\u2705 Enabled permanently");}disable(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null),this.stdin.off("data",this.handleStdinData);try{this.stdin.setRawMode(!1);}catch(e){oe("INPUT_MANAGER",`\u274C setRawMode(false) failed: ${e}`);}this.stdinListener=null,oe("INPUT_MANAGER","\u{1F53B} Disabled");}handleStdinData=e=>{let t=e.toString();oe("INPUT_MANAGER",`\u{1F4E5} Received ${t.length} bytes`),this.stdinListener?.(t);}},na=null;function sa(s){if(!na&&s&&(na=new ra(s)),!na)throw new Error("InputManager not initialized");return na}var oa=class{pendingRequests=new Map;frameScheduled=false;lastFrameTime=0;targetFPS=60;frameInterval=1e3/this.targetFPS;stats={totalFrames:0,droppedRequests:0,averageFrameTime:0};scheduleFrame(e,t,n=2){let r=Date.now();if(n===0){process.env.FRAME_SCHEDULER_DEBUG==="1"&&process.stderr.write(`[FRAME_SCHEDULER] \u26A1 IMMEDIATE render, executing now
|
|
194
194
|
`),this.flushFrame([{id:e,priority:n,callback:t,timestamp:r}]);return}let o=this.pendingRequests.get(e);if(o){n<o.priority?this.pendingRequests.set(e,{id:e,priority:n,callback:t,timestamp:r}):this.stats.droppedRequests++;return}this.pendingRequests.set(e,{id:e,priority:n,callback:t,timestamp:r}),this.frameScheduled||this.scheduleNextFrame();}scheduleNextFrame(){this.frameScheduled=true;let t=Date.now()-this.lastFrameTime,n=Math.max(0,this.frameInterval-t);setTimeout(()=>{this.executeFrame();},n);}executeFrame(){let e=Date.now(),t=Array.from(this.pendingRequests.values());this.pendingRequests.clear(),this.frameScheduled=false,t.sort((r,o)=>r.priority-o.priority),this.flushFrame(t),this.lastFrameTime=e,this.stats.totalFrames++;let n=Date.now()-e;this.stats.averageFrameTime=(this.stats.averageFrameTime*(this.stats.totalFrames-1)+n)/this.stats.totalFrames,process.env.FRAME_SCHEDULER_DEBUG==="1"&&process.stderr.write(`[FRAME_SCHEDULER] Frame #${this.stats.totalFrames}: ${t.length} requests, ${n.toFixed(2)}ms
|
|
195
195
|
`);}flushFrame(e){e.length!==0&&(process.env.FRAME_SCHEDULER_DEBUG==="1"&&process.stderr.write(`[FRAME_SCHEDULER] \u{1F3A8} Flushing ${e.length} render callback(s)
|
|
196
196
|
`),e.forEach(t=>{try{t.callback();}catch(n){process.stderr.write(`[FRAME_SCHEDULER] Render callback error: ${n}
|
|
197
|
-
`);}}));}getStats(){return {...this.stats}}resetStats(){this.stats={totalFrames:0,droppedRequests:0,averageFrameTime:0};}},nu=null;function go(){return nu||(nu=new oa),nu}Z();var ru="\x1B[200~",cg="\x1B[201~",Cx=50,ia=class{buffer="";inPaste=false;escapeTimeout=null;parse(e,t){for(
|
|
197
|
+
`);}}));}getStats(){return {...this.stats}}resetStats(){this.stats={totalFrames:0,droppedRequests:0,averageFrameTime:0};}},nu=null;function go(){return nu||(nu=new oa),nu}Z();var ru="\x1B[200~",cg="\x1B[201~",Cx=50,ia=class{buffer="";inPaste=false;escapeTimeout=null;parse(e,t){for(oe("PASTE_PARSER",`Received ${e.length} bytes: ${JSON.stringify(e)}`),this.buffer+=e;this.buffer.length>0;){if(this.inPaste){let l=this.buffer.indexOf(cg);if(l>=0){let c=this.buffer.slice(0,l);this.buffer=this.buffer.slice(l+cg.length),oe("PASTE_PARSER",`\u{1F4CB} Paste detected: ${c.length} chars`),t(c,true),this.inPaste=false;continue}else break}if(this.buffer.indexOf(ru)===0){this.escapeTimeout&&clearTimeout(this.escapeTimeout),oe("PASTE_PARSER","\u{1F4E5} Paste start detected"),this.inPaste=true,this.buffer=this.buffer.slice(ru.length);continue}if(this.buffer.startsWith("\x1B")){if(this.escapeTimeout&&clearTimeout(this.escapeTimeout),this.buffer.length===1){this.escapeTimeout=setTimeout(()=>{this.buffer==="\x1B"&&(oe("PASTE_PARSER","\u2328\uFE0F ESC key detected"),t("\x1B",false),this.buffer="");},Cx);break}if(this.isCompleteEscapeSequence(this.buffer)){oe("PASTE_PARSER",`\u2328\uFE0F ESC sequence: ${JSON.stringify(this.buffer)}`),t(this.buffer,false),this.buffer="";continue}if(this.buffer.length>20){oe("PASTE_PARSER",`\u26A0\uFE0F Invalid ESC sequence (too long): ${JSON.stringify(this.buffer)}`),t(this.buffer,false),this.buffer="";continue}break}let r=this.buffer.length,o=this.buffer.indexOf("\x1B"),i=this.buffer.indexOf(ru);o>0&&(r=Math.min(r,o)),i>0&&(r=Math.min(r,i));let a=this.buffer.slice(0,r);if(this.buffer=this.buffer.slice(r),a.length>0&&(oe("PASTE_PARSER",`\u2328\uFE0F Text: ${JSON.stringify(a)} (${a.length} chars)`),t(a,false)),a.length===0&&this.buffer.length>0)break}}isCompleteEscapeSequence(e){return e.startsWith("\x1B[")?/[A-Za-z~^$u]$/.test(e):e.startsWith("\x1BO")?/[A-Za-z]$/.test(e):e.startsWith("\x1B]")?e.endsWith("\x07")||e.endsWith("\x1B\\"):e.length===2}dispose(){this.escapeTimeout&&(clearTimeout(this.escapeTimeout),this.escapeTimeout=null),this.buffer="",this.inPaste=false,oe("PASTE_PARSER","\u{1F5D1}\uFE0F Disposed");}};Z();var xx=(s,e=2)=>s.replace(/^\t+/gm,t=>" ".repeat(t.length*e)),ug=xx;var Tx=(s,e)=>{let t=[],n=s-e,r=s+e;for(let o=n;o<=r;o++)t.push(o);return t},wx=(s,e,t={})=>{var n;if(typeof s!="string")throw new TypeError("Source code is missing.");if(!e||e<1)throw new TypeError("Line number must start from `1`.");let r=ug(s).split(/\r?\n/);if(!(e>r.length))return Tx(e,(n=t.around)!==null&&n!==void 0?n:3).filter(o=>r[o-1]!==void 0).map(o=>({line:o,value:r[o-1]}))},dg=wx;var or=createContext({isScreenReaderEnabled:false});var aa=createContext(void 0);var pg=forwardRef(({children:s,backgroundColor:e,"aria-label":t,"aria-hidden":n,"aria-role":r,"aria-state":o,...i},a)=>{let{isScreenReaderEnabled:l}=useContext(or),c=t?I.createElement("ink-text",null,t):void 0;if(l&&n)return null;let u=I.createElement("ink-box",{ref:a,style:{flexWrap:"nowrap",flexDirection:"row",flexGrow:0,flexShrink:1,...i,backgroundColor:e,overflowX:i.overflowX??i.overflow??"visible",overflowY:i.overflowY??i.overflow??"visible"},internal_accessibility:{role:r,state:o}},l&&c?c:s);return e?I.createElement(aa.Provider,{value:e},u):u});pg.displayName="Box";var S=pg;function y({color:s,backgroundColor:e,dimColor:t=false,bold:n=false,italic:r=false,underline:o=false,strikethrough:i=false,inverse:a=false,wrap:l="wrap",children:c,"aria-label":u,"aria-hidden":d=false}){let{isScreenReaderEnabled:m}=useContext(or),g=useContext(aa),h=m&&u?u:c;if(h==null)return null;let f=v=>{t&&(v=Ie.dim(v)),s&&(v=Tn(v,s,"foreground"));let b=e??g;return b&&(v=Tn(v,b,"background")),n&&(v=Ie.bold(v)),r&&(v=Ie.italic(v)),o&&(v=Ie.underline(v)),i&&(v=Ie.strikethrough(v)),a&&(v=Ie.inverse(v)),v};return m&&d?null:I.createElement("ink-text",{style:{flexGrow:0,flexShrink:1,flexDirection:"row",textWrap:l},internal_transform:f},m&&u?u:c)}var ou=s=>s?.replace(`file://${cwd()}/`,""),hg=new gg({cwd:cwd(),internals:gg.nodeInternals()});function iu({error:s}){let e=s.stack?s.stack.split(`
|
|
198
198
|
`).slice(1):void 0,t=e?hg.parseLine(e[0]):void 0,n=ou(t?.file),r,o=0;if(n&&t?.line&&Je.existsSync(n)){let i=Je.readFileSync(n,"utf8");if(r=dg(i,t.line),r)for(let{line:a}of r)o=Math.max(o,String(a).length);}return I.createElement(S,{flexDirection:"column",padding:1},I.createElement(S,null,I.createElement(y,{backgroundColor:"red",color:"white"}," ","ERROR"," "),I.createElement(y,null," ",s.message)),t&&n&&I.createElement(S,{marginTop:1},I.createElement(y,{dimColor:true},n,":",t.line,":",t.column)),t&&r&&I.createElement(S,{marginTop:1,flexDirection:"column"},r.map(({line:i,value:a})=>I.createElement(S,{key:i},I.createElement(S,{width:o+1},I.createElement(y,{dimColor:i!==t.line,backgroundColor:i===t.line?"red":void 0,color:i===t.line?"white":void 0,"aria-label":i===t.line?`Line ${i}, error`:`Line ${i}`},String(i).padStart(o," "),":")),I.createElement(y,{key:i,backgroundColor:i===t.line?"red":void 0,color:i===t.line?"white":void 0}," "+a)))),s.stack&&I.createElement(S,{marginTop:1,flexDirection:"column"},s.stack.split(`
|
|
199
|
-
`).slice(1).map(i=>{let a=hg.parseLine(i);return a?I.createElement(S,{key:i},I.createElement(y,{dimColor:true},"- "),I.createElement(y,{dimColor:true,bold:true},a.function),I.createElement(y,{dimColor:true,color:"gray","aria-label":`at ${ou(a.file)??""} line ${a.line} column ${a.column}`}," ","(",ou(a.file)??"",":",a.line,":",a.column,")")):I.createElement(S,{key:i},I.createElement(y,{dimColor:true},"- "),I.createElement(y,{dimColor:true,bold:true},i,"\\t"," "))})))}var Fx=" ",Ux="\x1B[Z",jx="\x1B",yo=class extends PureComponent{static displayName="InternalApp";static getDerivedStateFromError(e){return {error:e}}state={isFocusEnabled:true,activeFocusId:void 0,focusables:[],error:void 0,terminalColumns:Qt.stdout.columns||80,terminalRows:Qt.stdout.rows||24};internal_eventEmitter=new EventEmitter;pasteParser=null;isRawModeSupported(){return this.props.stdin.isTTY}render(){return I.createElement(ea.Provider,{value:{exit:this.handleExit}},I.createElement(Zr.Provider,{value:{stdin:this.props.stdin,setRawMode:this.handleSetRawMode,isRawModeSupported:this.isRawModeSupported(),internal_exitOnCtrlC:this.props.exitOnCtrlC,internal_eventEmitter:this.internal_eventEmitter}},I.createElement(mo.Provider,{value:{stdout:this.props.stdout,write:this.props.writeToStdout,columns:this.state.terminalColumns,rows:this.state.terminalRows}},I.createElement(tu.Provider,{value:{stderr:this.props.stderr,write:this.props.writeToStderr}},I.createElement(ta.Provider,{value:{activeId:this.state.activeFocusId,add:this.addFocusable,remove:this.removeFocusable,activate:this.activateFocusable,deactivate:this.deactivateFocusable,enableFocus:this.enableFocus,disableFocus:this.disableFocus,focusNext:this.focusNext,focusPrevious:this.focusPrevious,focus:this.focus}},this.state.error?I.createElement(iu,{error:this.state.error}):this.props.children)))))}componentDidMount(){Zi.hide(this.props.stdout),this.props.stdin.isTTY&&(this.props.stdout.write("\x1B[?2004h"),
|
|
200
|
-
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`)};handleInput=e=>{e===""&&this.props.exitOnCtrlC&&this.handleExit(),e===jx&&this.state.activeFocusId&&this.setState({activeFocusId:void 0}),this.state.isFocusEnabled&&this.state.focusables.length>0&&(e===Fx&&this.focusNext(),e===Ux&&this.focusPrevious());};handlePaste=async e=>{if(
|
|
199
|
+
`).slice(1).map(i=>{let a=hg.parseLine(i);return a?I.createElement(S,{key:i},I.createElement(y,{dimColor:true},"- "),I.createElement(y,{dimColor:true,bold:true},a.function),I.createElement(y,{dimColor:true,color:"gray","aria-label":`at ${ou(a.file)??""} line ${a.line} column ${a.column}`}," ","(",ou(a.file)??"",":",a.line,":",a.column,")")):I.createElement(S,{key:i},I.createElement(y,{dimColor:true},"- "),I.createElement(y,{dimColor:true,bold:true},i,"\\t"," "))})))}var Fx=" ",Ux="\x1B[Z",jx="\x1B",yo=class extends PureComponent{static displayName="InternalApp";static getDerivedStateFromError(e){return {error:e}}state={isFocusEnabled:true,activeFocusId:void 0,focusables:[],error:void 0,terminalColumns:Qt.stdout.columns||80,terminalRows:Qt.stdout.rows||24};internal_eventEmitter=new EventEmitter;pasteParser=null;isRawModeSupported(){return this.props.stdin.isTTY}render(){return I.createElement(ea.Provider,{value:{exit:this.handleExit}},I.createElement(Zr.Provider,{value:{stdin:this.props.stdin,setRawMode:this.handleSetRawMode,isRawModeSupported:this.isRawModeSupported(),internal_exitOnCtrlC:this.props.exitOnCtrlC,internal_eventEmitter:this.internal_eventEmitter}},I.createElement(mo.Provider,{value:{stdout:this.props.stdout,write:this.props.writeToStdout,columns:this.state.terminalColumns,rows:this.state.terminalRows}},I.createElement(tu.Provider,{value:{stderr:this.props.stderr,write:this.props.writeToStderr}},I.createElement(ta.Provider,{value:{activeId:this.state.activeFocusId,add:this.addFocusable,remove:this.removeFocusable,activate:this.activateFocusable,deactivate:this.deactivateFocusable,enableFocus:this.enableFocus,disableFocus:this.disableFocus,focusNext:this.focusNext,focusPrevious:this.focusPrevious,focus:this.focus}},this.state.error?I.createElement(iu,{error:this.state.error}):this.props.children)))))}componentDidMount(){Zi.hide(this.props.stdout),this.props.stdin.isTTY&&(this.props.stdout.write("\x1B[?2004h"),oe("INK_APP","\u2705 Bracketed Paste Mode enabled"),this.pasteParser=new ia,sa(this.props.stdin).enablePermanent(t=>{this.pasteParser.parse(t,(n,r)=>{r?this.handlePaste(n):this.handleInput(n),this.internal_eventEmitter.emit("input",n);});}),oe("INK_APP","\u2705 InputManager and PasteParser initialized"),Qt.env.FRAME_SCHEDULER_DEBUG==="1"&&setInterval(()=>{let t=go().getStats();oe("FRAME_SCHEDULER","Stats",t);},5e3)),this.props.stdout.write("\x1B[?1000l"),this.props.stdout.write("\x1B[?1002l"),this.props.stdout.write("\x1B[?1006l"),this.props.stdout.on("resize",this.handleResize);}handleResize=()=>{this.props.onResize?.(),this.setState({terminalColumns:this.props.stdout.columns||80,terminalRows:this.props.stdout.rows||24});};componentWillUnmount(){if(Zi.show(this.props.stdout),this.props.stdout.off("resize",this.handleResize),this.isRawModeSupported()){this.props.stdout.write("\x1B[?2004l"),this.pasteParser?.dispose(),this.pasteParser=null;try{sa().disable();}catch{}oe("INK_APP","\u{1F53B} Bracketed Paste Mode disabled and resources cleaned up");}}componentDidCatch(e){this.handleExit(e);}handleSetRawMode=e=>{if(!this.isRawModeSupported())throw new Error(`Raw mode is not supported on the current stdin.
|
|
200
|
+
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`)};handleInput=e=>{e===""&&this.props.exitOnCtrlC&&this.handleExit(),e===jx&&this.state.activeFocusId&&this.setState({activeFocusId:void 0}),this.state.isFocusEnabled&&this.state.focusables.length>0&&(e===Fx&&this.focusNext(),e===Ux&&this.focusPrevious());};handlePaste=async e=>{if(oe("INPUT_PASTE",`\u{1F4CB} Pasted ${e.length} characters`),e.length===0){oe("INPUT_PASTE","\u{1F5BC}\uFE0F Empty paste detected - checking clipboard for image...");try{let{pasteImageAsBase64:t}=await Promise.resolve().then(()=>(uu(),Tg)),n=await t();if(n){oe("INPUT_PASTE",`\u{1F4CE} Image detected in clipboard: ${n.name} (${Math.round(n.data.length/1024)}KB)`),this.internal_eventEmitter.emit("image-paste",n);return}}catch(t){oe("INPUT_PASTE","\u274C Failed to check clipboard for image",{error:t});}}this.internal_eventEmitter.emit("paste",e),this.handleInput(e);};handleExit=e=>{this.isRawModeSupported()&&this.handleSetRawMode(false),this.props.onExit(e);};enableFocus=()=>{this.setState({isFocusEnabled:true});};disableFocus=()=>{this.setState({isFocusEnabled:false});};focus=e=>{this.setState(t=>t.focusables.some(r=>r?.id===e)?{activeFocusId:e}:t);};focusNext=()=>{this.setState(e=>{let t=e.focusables.find(r=>r.isActive)?.id;return {activeFocusId:this.findNextFocusable(e)??t}});};focusPrevious=()=>{this.setState(e=>{let t=e.focusables.findLast(r=>r.isActive)?.id;return {activeFocusId:this.findPreviousFocusable(e)??t}});};addFocusable=(e,{autoFocus:t})=>{this.setState(n=>{let r=n.activeFocusId;return !r&&t&&(r=e),{activeFocusId:r,focusables:[...n.focusables,{id:e,isActive:true}]}});};removeFocusable=e=>{this.setState(t=>({activeFocusId:t.activeFocusId===e?void 0:t.activeFocusId,focusables:t.focusables.filter(n=>n.id!==e)}));};activateFocusable=e=>{this.setState(t=>({focusables:t.focusables.map(n=>n.id!==e?n:{id:e,isActive:true})}));};deactivateFocusable=e=>{this.setState(t=>({activeFocusId:t.activeFocusId===e?void 0:t.activeFocusId,focusables:t.focusables.map(n=>n.id!==e?n:{id:e,isActive:false})}));};findNextFocusable=e=>{let t=e.focusables.findIndex(n=>n.id===e.activeFocusId);for(let n=t+1;n<e.focusables.length;n++){let r=e.focusables[n];if(r?.isActive)return r.id}};findPreviousFocusable=e=>{let t=e.focusables.findIndex(n=>n.id===e.activeFocusId);for(let n=t-1;n>=0;n--){let r=e.focusables[n];if(r?.isActive)return r.id}}};var Sg=()=>{},bo=class{options;log;throttledLog;isScreenReaderEnabled;isUnmounted;lastOutput;lastOutputHeight;lastTerminalWidth;container;rootNode;exitPromise;restoreConsole;unsubscribeResize;constructor(e){Hx(this),this.options=e,this.rootNode=qi("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.isScreenReaderEnabled=e.isScreenReaderEnabled??Qt.env.INK_SCREEN_READER==="true";let t=e.debug||this.isScreenReaderEnabled;e.maxFps??30;let o=go();this.rootNode.onRender=()=>{let i=t?0:2;if(o.scheduleFrame("ink-root-render",this.onRender,i),Qt.env.NEOX_INK_DEBUG==="1"){let a=t?"IMMEDIATE":"NORMAL";Qt.stderr.write(`[INK] \u{1F4C5} Render scheduled with ${a} priority
|
|
201
201
|
`);}},this.rootNode.onImmediateRender=()=>{o.scheduleFrame("ink-root-immediate",this.onRender,0),Qt.env.NEOX_INK_DEBUG==="1"&&Qt.stderr.write(`[INK] \u{1F680} Render scheduled with IMMEDIATE priority
|
|
202
202
|
`);},this.log=rg.create(e.stdout,{incremental:e.incrementalRendering}),this.throttledLog=t?this.log:throttle(this.log,void 0,{leading:true,trailing:true}),this.isUnmounted=false,this.lastOutput="",this.lastOutputHeight=0,this.lastTerminalWidth=this.getTerminalWidth(),this.container=Un.createContainer(this.rootNode,LegacyRoot,null,false,null,"id",()=>{},()=>{},()=>{},()=>{},null),this.unsubscribeExit=onExit(this.unmount,{alwaysLast:false}),Qt.env.DEV==="true"&&Un.injectIntoDevTools({bundleType:0,version:"16.13.1",rendererPackageName:"ink"}),e.patchConsole&&this.patchConsole();}getTerminalWidth=()=>this.options.stdout.columns||80;resized=()=>{this.options.debug||this.log.clear(),this.lastTerminalWidth=this.getTerminalWidth(),this.calculateLayout();};handleResizeFromApp=()=>{if(!this.options.debug){let e=this.getTerminalWidth(),t=this.lastTerminalWidth;if(e<t&&this.lastOutput){let n=this.lastOutput.split(`
|
|
203
203
|
`),r=0;for(let o of n){let i=o.replace(/\u001B\[[0-9;]*m/g,"").length;i>e&&(r+=Math.ceil(i/e)-1);}this.options.stdout.write(wn.eraseLines(this.lastOutputHeight+r)),this.log.sync("");}else this.log.clear();}this.lastTerminalWidth=this.getTerminalWidth(),this.lastOutput="",this.lastOutputHeight=0,this.calculateLayout();};resolveExitPromise=()=>{};rejectExitPromise=()=>{};unsubscribeExit=()=>{};calculateLayout=()=>{let e=this.getTerminalWidth();this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,ye.DIRECTION_LTR);};onRender=()=>{if(this.isUnmounted)return;Qt.env.NEOX_INK_DEBUG==="1"&&Qt.stderr.write(`[INK_RENDER] \u{1F3AC} onRender called, starting actual render
|
|
@@ -208,7 +208,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
|
|
|
208
208
|
`;this.options.stdout.write(a),this.log.sync(t);}else t!==this.lastOutput&&this.throttledLog(t);this.lastOutput=t,this.lastOutputHeight=n,Qt.env.NEOX_INK_DEBUG==="1"&&Qt.stderr.write(`[INK_RENDER] \u2705 onRender completed
|
|
209
209
|
`);};render(e){let t=I.createElement(or.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},I.createElement(yo,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,exitOnCtrlC:this.options.exitOnCtrlC,onExit:this.unmount,onResize:this.handleResizeFromApp},e));Un.updateContainerSync(t,this.container,null,Sg),Un.flushSyncWork();}writeToStdout(e){if(!this.isUnmounted){if(this.options.debug){this.options.stdout.write(e+this.lastOutput);return}if(ns){this.options.stdout.write(e);return}this.log.clear(),this.options.stdout.write(e),this.log(this.lastOutput);}}writeToStderr(e){if(!this.isUnmounted){if(this.options.debug){this.options.stderr.write(e),this.options.stdout.write(this.lastOutput);return}if(ns){this.options.stderr.write(e);return}this.log.clear(),this.options.stderr.write(e),this.log(this.lastOutput);}}unmount(e){this.isUnmounted||(this.calculateLayout(),this.onRender(),this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),ns?this.options.stdout.write(this.lastOutput+`
|
|
210
210
|
`):this.options.debug||this.log.done(),this.isUnmounted=true,Un.updateContainerSync(null,this.container,null,Sg),Un.flushSyncWork(),Qr.delete(this.options.stdout),e instanceof Error?this.rejectExitPromise(e):this.resolveExitPromise());}async waitUntilExit(){return this.exitPromise||=new Promise((e,t)=>{this.resolveExitPromise=e,this.rejectExitPromise=t;}),this.exitPromise}clear(){!ns&&!this.options.debug&&this.log.clear();}patchConsole(){this.options.debug||(this.restoreConsole=qx((e,t)=>{e==="stdout"&&this.writeToStdout(t),e==="stderr"&&(t.startsWith("The above error occurred")||this.writeToStderr(t));}));}};var Xx=(s,e)=>{let t={stdout:Qt.stdout,stdin:Qt.stdin,stderr:Qt.stderr,debug:false,exitOnCtrlC:true,patchConsole:true,maxFps:30,incrementalRendering:true,...Qx(e)},n=Zx(t.stdout,()=>new bo(t));return n.render(s),{rerender:n.render,unmount(){n.unmount();},waitUntilExit:n.waitUntilExit,cleanup:()=>Qr.delete(t.stdout),clear:n.clear}},rs=Xx,Qx=(s={})=>s instanceof Stream?{stdout:s,stdin:Qt.stdin}:s,Zx=(s,e)=>{let t=Qr.get(s);return t||(t=e(),Qr.set(s,t)),t};function ua(s){let{items:e,children:t,style:n}=s,[r,o]=useState(0),i=useMemo(()=>e.slice(r),[r,e]);useLayoutEffect(()=>{o(e.length);},[e.length]);let a=useMemo(()=>i.map((c,u)=>t(c,r+u)),[i,t,r]),l=useMemo(()=>({position:"absolute",flexDirection:"column",...n}),[n]);return I.createElement("ink-box",{internal_static:true,style:l},a)}var sT=/^(?:\x1b)([a-zA-Z0-9])$/,oT=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,_g={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},Ig=[...Object.values(_g),"backspace"],iT=s=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(s),aT=s=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(s),lT=(s="")=>{let e;Buffer$1.isBuffer(s)?s[0]>127&&s[1]===void 0?(s[0]-=128,s="\x1B"+String(s)):s=String(s):s!==void 0&&typeof s!="string"?s=String(s):s||(s="");let t={name:"",ctrl:false,meta:false,shift:false,option:false,sequence:s,raw:s};if(t.sequence=t.sequence||s||t.name,s==="\r")t.raw=void 0,t.name="return";else if(s===`
|
|
211
|
-
`)t.name="enter";else if(s===" ")t.name="tab";else if(s==="\b"||s==="\x1B\b")t.name="backspace",t.meta=s.charAt(0)==="\x1B";else if(s==="\x7F"||s==="\x1B\x7F")t.name="delete",t.meta=s.charAt(0)==="\x1B";else if(s==="\x1B"||s==="\x1B\x1B")t.name="escape",t.meta=s.length===2;else if(s===" "||s==="\x1B ")t.name="space",t.meta=s.length===2;else if(s.length===1&&s<="")t.name=String.fromCharCode(s.charCodeAt(0)+97-1),t.ctrl=true;else if(s.length===1&&s>="0"&&s<="9")t.name="number";else if(s.length===1&&s>="a"&&s<="z")t.name=s;else if(s.length===1&&s>="A"&&s<="Z")t.name=s.toLowerCase(),t.shift=true;else if(e=sT.exec(s))t.meta=true,t.shift=/^[A-Z]$/.test(e[1]);else if(e=oT.exec(s)){let n=[...s];n[0]==="\x1B"&&n[1]==="\x1B"&&(t.option=true);let r=[e[1],e[2],e[4],e[6]].filter(Boolean).join(""),o=(e[3]||e[5]||1)-1;t.ctrl=!!(o&4),t.meta=!!(o&10),t.shift=!!(o&1),t.code=r,t.name=_g[r],t.shift=iT(r)||t.shift,t.ctrl=aT(r)||t.ctrl;}return t},Eg=lT;var uT=()=>useContext(Zr),da=uT;Z();var dT=(s,e={})=>{let{stdin:t,setRawMode:n,internal_exitOnCtrlC:r,internal_eventEmitter:o}=da();useEffect(()=>{if(e.isActive!==false)return ()=>{}},[e.isActive,n]),useEffect(()=>{if(e.isActive===false)return;let i=a=>{let l=Date.now();
|
|
211
|
+
`)t.name="enter";else if(s===" ")t.name="tab";else if(s==="\b"||s==="\x1B\b")t.name="backspace",t.meta=s.charAt(0)==="\x1B";else if(s==="\x7F"||s==="\x1B\x7F")t.name="delete",t.meta=s.charAt(0)==="\x1B";else if(s==="\x1B"||s==="\x1B\x1B")t.name="escape",t.meta=s.length===2;else if(s===" "||s==="\x1B ")t.name="space",t.meta=s.length===2;else if(s.length===1&&s<="")t.name=String.fromCharCode(s.charCodeAt(0)+97-1),t.ctrl=true;else if(s.length===1&&s>="0"&&s<="9")t.name="number";else if(s.length===1&&s>="a"&&s<="z")t.name=s;else if(s.length===1&&s>="A"&&s<="Z")t.name=s.toLowerCase(),t.shift=true;else if(e=sT.exec(s))t.meta=true,t.shift=/^[A-Z]$/.test(e[1]);else if(e=oT.exec(s)){let n=[...s];n[0]==="\x1B"&&n[1]==="\x1B"&&(t.option=true);let r=[e[1],e[2],e[4],e[6]].filter(Boolean).join(""),o=(e[3]||e[5]||1)-1;t.ctrl=!!(o&4),t.meta=!!(o&10),t.shift=!!(o&1),t.code=r,t.name=_g[r],t.shift=iT(r)||t.shift,t.ctrl=aT(r)||t.ctrl;}return t},Eg=lT;var uT=()=>useContext(Zr),da=uT;Z();var dT=(s,e={})=>{let{stdin:t,setRawMode:n,internal_exitOnCtrlC:r,internal_eventEmitter:o}=da();useEffect(()=>{if(e.isActive!==false)return ()=>{}},[e.isActive,n]),useEffect(()=>{if(e.isActive===false)return;let i=a=>{let l=Date.now();oe("INPUT",`>>> handleData START, data.length=${a.length}`);let c=Eg(a),u={upArrow:c.name==="up",downArrow:c.name==="down",leftArrow:c.name==="left",rightArrow:c.name==="right",pageDown:c.name==="pagedown",pageUp:c.name==="pageup",home:c.name==="home",end:c.name==="end",return:c.name==="return",escape:c.name==="escape",ctrl:c.ctrl,shift:c.shift,tab:c.name==="tab",backspace:c.name==="backspace",delete:c.name==="delete",meta:c.meta||c.name==="escape"||c.option},d=c.ctrl?c.name:c.sequence;if(Ig.includes(c.name)&&(d=""),d.startsWith("\x1B")&&(d=d.slice(1)),d.length===1&&typeof d[0]=="string"&&/[A-Z]/.test(d[0])&&(u.shift=true),!(d==="c"&&u.ctrl)||!r){let m=Date.now();oe("INPUT",`>>> Before batchedUpdates, elapsed=${m-l}ms`),Un.batchedUpdates(()=>{s(d,u);});let g=Date.now();oe("INPUT",`<<< After batchedUpdates, duration=${g-m}ms, total=${g-l}ms`);}};return o?.on("input",i),()=>{o?.removeListener("input",i);}},[e.isActive,t,r,s]);},et=dT;var mT=()=>useContext(ea),vo=mT;var hT=()=>useContext(mo),Co=hT;function pa(s){return {output_info:s,behavior:{type:"allow"}}}function Mg(s,e){return {output_info:e,behavior:{type:"reject_content",message:s}}}function xo(s){return {type:"message",data:s}}function ss(){let s=new Date,e=s.toISOString().slice(0,10).replace(/-/g,""),t=s.toISOString().slice(11,19).replace(/:/g,""),n=Math.random().toString(36).slice(2,6);return `session_${e}_${t}_${n}`}function fT(s){let e=s.match(/Error\s+(?:code\s+)?(\d{3})/i);if(e)return e[1];let t=s.match(/(\d{3}):\s*([^<\n]+)/);return t?t[1]:null}function yT(s){let e=s.match(/<title>[^|]*\|\s*\d{3}:\s*([^<]+)<\/title>/i);if(e)return e[1].trim();let t=s.match(/<h1[^>]*>(?:<[^>]+>)*([^<]+?(?:\s+\d{3})?)<\/(?:[^>]+>)*<\/h1>/i);if(t)return t[1].replace(/Error code\s+\d{3}/i,"").trim();let n=s.match(/Error\s+code\s+(\d{3})/i);if(n){let o=n[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"}[o]||"Server error"}let r=s.match(/<span[^>]*class="inline-block"[^>]*>([^<]+)<\/span>/i);return r?r[1].trim():null}function bT(s){let e=s.match(/truncate[^>]*>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})<\/span>/);if(e)return e[1];let t=s.match(/<title>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:null}function To(s){return s.trim().startsWith("<!DOCTYPE html")||s.trim().startsWith("<html")||/<html[^>]*>/i.test(s)}function vT(s){let e=s.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function _r(s,e){let t=vT(s);if(t)try{let i=JSON.parse(t);if(i.error){let a=i.error,l=a.type||a.code||(e?`HTTP_${e}`:"API_ERROR"),c=a.message||"API error",u;if(a.type==="usage_limit_reached"){let d=a.resets_at?new Date(a.resets_at*1e3).toLocaleString():void 0,m=a.resets_in_seconds;if(m){let g=Math.floor(m/3600),h=Math.floor(m%3600/60);u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets in ${g}h ${h}m.`;}else d&&(u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets at ${d}.`);}return {code:l,message:c,detail:u}}}catch{}if(s.trim().startsWith("{"))try{let i=JSON.parse(s);if(i.error){let a=i.error;return {code:a.type||a.code||(e?`HTTP_${e}`:"API_ERROR"),message:a.message||"API error"}}}catch{}if(To(s)){let i=fT(s)||String(e||"UNKNOWN"),a=yT(s)||"Server error",l=bT(s),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:a,detail:c}}let n=s.match(/OpenAI.*error:\s*(\d+)\s*-\s*(.*)/i);if(n){let i=n[1],a=n[2];if(To(a)){let l=_r(a,parseInt(i,10));return {code:l.code,message:l.message,detail:l.detail}}return a=a.trim(),a.length>200&&(a=a.slice(0,200)+"..."),{code:`HTTP_${i}`,message:a}}let r=s.match(/Anthropic.*error:\s*(\d+)\s*-\s*(.*)/i);if(r){let i=r[1],a=r[2].trim();return a.length>200&&(a=a.slice(0,200)+"..."),{code:`HTTP_${i}`,message:a}}if(s.includes("ECONNREFUSED"))return {code:"NETWORK_ERROR",message:"Connection refused",detail:"Unable to connect to the API server. Please check your network connection."};if(s.includes("ETIMEDOUT")||s.includes("timeout"))return {code:"TIMEOUT",message:"Connection timeout",detail:"The request took too long to complete. Please try again."};if(s.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(s)||/maximum.*context.*length/i.test(s))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(s)||s.includes("429"))return {code:"RATE_LIMIT",message:"Rate limit exceeded",detail:"Too many requests. Please wait a moment before trying again."};if(s.includes("401")||/unauthorized/i.test(s))return {code:"AUTH_ERROR",message:"Authentication failed",detail:"Please check your API key in settings."};if(s.includes("403")||/forbidden/i.test(s))return {code:"FORBIDDEN",message:"Access denied",detail:"Your API key does not have permission for this operation."};let o=s;return o=o.replace(/^Error:\s*/i,""),o=o.replace(/^Request failed with status code\s+\d+:\s*/i,""),o.length>300&&(o=o.slice(0,300)+"..."),{code:e?`HTTP_${e}`:"UNKNOWN",message:o}}var Le=class s 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,s);}withContext(e){return new s({...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 Gn(s){if(!s)return;if(typeof s!="string")return typeof s=="number"&&s>0?Math.ceil(s*1e3):void 0;let e=s.trim(),t=e.match(/^(\d+(?:\.\d+)?)\s*ms$/i);if(t){let o=parseFloat(t[1]);return o>0?Math.ceil(o):void 0}let n=parseFloat(e);if(!isNaN(n)&&n>0)return Math.ceil(n*1e3);let r=new Date(e);if(!isNaN(r.getTime())){let o=r.getTime()-Date.now();return o>0?Math.ceil(o):void 0}}function CT(s){switch(s){case 502:return 3e3;case 503:return 5e3;case 504:return 2e3;default:return 2e3}}function ma(s){if(!s)return;let e=s["retry-after"]||s["Retry-After"];if(e){let o=Gn(e);if(o)return o}let t=s["retry-after-ms"]||s["Retry-After-Ms"];if(t){let o=parseFloat(t);if(!isNaN(o)&&o>0)return Math.ceil(o)}let n=s["x-ratelimit-reset-requests"];if(n){let o=Gn(n);if(o)return o}let r=s["anthropic-ratelimit-requests-reset"];if(r){let o=new Date(r);if(!isNaN(o.getTime())){let i=o.getTime()-Date.now();return i>0?Math.ceil(i):void 0}}}function gu(s){return typeof s=="object"&&s!==null&&"message"in s&&typeof s.message=="string"}function Pg(s){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(s))}function xT(s){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(s))}function TT(s){if(s){if(typeof s=="string")return s;if(typeof s=="object"){if(typeof s.error=="string")return s.error;if(s.error?.message)return s.error.message;if(s.message)return s.message}}}function Zt(s){if(s instanceof Le)return s;let e=s instanceof Error?s.message:String(s),t=s instanceof Error?s:void 0,n=gu(s)?s:void 0,o=(n?TT(n.response?.data):void 0)||e;if(n?.response?.status){let i=n.response.status,a=ma(n.response.headers),l=n.response.headers?.["x-request-id"]||n.response.headers?.["cf-ray"];if(i===429){let c=n.response.data,u=c?.error?.type;return u==="usage_limit_reached"||u==="usage_not_included"?new Le({category:"fatal_limit",code:"USAGE_LIMIT_REACHED",message:c?.error?.message||"Usage limit reached",retryable:false,context:{httpStatus:i,requestId:l},originalError:t}):new Le({category:"retryable_http",code:`HTTP_${i}`,message:o,retryable:true,retryAfter:a,context:{httpStatus:i,requestId:l},originalError:t})}if(i===502||i===503||i===504){let c=o;if(To(o)){let d=_r(o,i);c=d.message,d.detail&&(c+=`
|
|
212
212
|
`+d.detail);}let u=a||CT(i);return new Le({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:o},originalError:t})}if(i>=500){let c=o;if(To(o)){let u=_r(o,i);c=u.message,u.detail&&(c+=`
|
|
213
213
|
`+u.detail);}return new Le({category:"retryable_http",code:`HTTP_${i}`,message:c,retryable:true,retryAfter:a,context:{httpStatus:i,requestId:l,rawMessage:o},originalError:t})}if(i===401)return new Le({category:"fatal_auth",code:"UNAUTHORIZED",message:o||"Authentication failed. Please check your API key.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===403)return new Le({category:"fatal_auth",code:"FORBIDDEN",message:o||"Access denied. Please check your API permissions.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===400)return Pg(e)?new Le({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}):o.includes("Upstream request failed")||o.includes("upstream")||o.includes("gateway")?new Le({category:"retryable_http",code:"PROXY_UPSTREAM_FAILED",message:o||"Proxy upstream request failed",retryable:true,context:{httpStatus:i,requestId:l},originalError:t}):new Le({category:"fatal_invalid",code:"INVALID_REQUEST",message:o,retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i>=400&&i<500)return new Le({category:"fatal_invalid",code:`HTTP_${i}`,message:o,retryable:false,context:{httpStatus:i,requestId:l},originalError:t})}if(gu(s)){let i=s.code,a=s.name;if(i==="ERR_CANCELED"||a==="CanceledError"||a==="AbortError")return new Le({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:t});if(i==="ECONNREFUSED"||i==="ENOTFOUND"||i==="ECONNRESET")return new Le({category:"retryable_network",code:i,message:`Network error: ${e}`,retryable:true,originalError:t});if(i==="ETIMEDOUT"||i==="ESOCKETTIMEDOUT")return new Le({category:"retryable_network",code:"TIMEOUT",message:`Connection timeout: ${e}`,retryable:true,originalError:t})}return s instanceof Error&&s.name==="AbortError"?new Le({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:s}):gu(s)&&s.code==="STREAM_INCOMPLETE"?new Le({category:"retryable_stream",code:"STREAM_INCOMPLETE",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,context:{toolName:s.toolName,rawMessage:e},originalError:t}):s?.code==="STREAM_TIMEOUT"?new Le({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 Le({category:"retryable_stream",code:"STREAM_ERROR",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,originalError:t}):Pg(e)?new Le({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,originalError:t}):xT(e)?new Le({category:"fatal_limit",code:"QUOTA_EXCEEDED",message:e,retryable:false,originalError:t}):new Le({category:"internal",code:"UNKNOWN",message:e,retryable:false,originalError:t})}function Rg(s,e,t){let n=e||"";return n.trim().endsWith("}")?(s==="write_file"||s==="edit_file")&&!n.includes('"content"')?new Le({category:"tool_truncated",code:"TOOL_MISSING_CONTENT",message:"The content field is missing (likely truncated)",retryable:false,context:{toolName:s,receivedLength:n.length,rawMessage:t.message},originalError:t}):t.message.includes("JSON")||t.message.includes("Unexpected")||t.message.includes("parse")?new Le({category:"tool_json_invalid",code:"JSON_PARSE_ERROR",message:`Invalid JSON in tool arguments: ${t.message}`,retryable:true,context:{toolName:s,receivedLength:n.length,rawMessage:t.message},originalError:t}):new Le({category:"tool_json_invalid",code:"TOOL_ERROR",message:t.message,retryable:true,context:{toolName:s},originalError:t}):new Le({category:"tool_truncated",code:"TOOL_ARGS_TRUNCATED",message:"Tool arguments were truncated during streaming",retryable:false,context:{toolName:s,receivedLength:n.length,rawMessage:t.message},originalError:t})}function ga(s){switch(s.category){case "retryable_rate_limit":return `API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${s.retryAfter?Math.ceil(s.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 Wn={requestMaxRetries:10,streamMaxRetries:5,toolMaxRetries:2,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:3e4,jitterRange:.2,streamIdleTimeoutMs:3e5};function ar(s,e){return {...Wn,...s,...e?.requestMaxRetries!==void 0&&{requestMaxRetries:e.requestMaxRetries},...e?.streamMaxRetries!==void 0&&{streamMaxRetries:e.streamMaxRetries},...e?.streamIdleTimeoutMs!==void 0&&{streamIdleTimeoutMs:e.streamIdleTimeoutMs}}}var ir={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 os(s,e){let t=s.toLowerCase();if(t.includes("yunwu"))return ir.yunwu;if(t.includes("azure"))return ir.azure;if(e){let n=e.toLowerCase();if(n.includes("yunwu"))return ir.yunwu;if(n.includes("azure"))return ir.azure;if(!(n.includes("api.anthropic.com")||n.includes("api.openai.com")))return ir.proxy}return t.includes("anthropic")?ir.anthropic:t.includes("gemini")?ir.gemini:ir.openai}var Dg=100,Ng=200,Lg=1800*1e3;var wo=class extends Error{constructor(e){super(e),this.name="GuardrailTripwireTriggered";}},is=class extends wo{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}}},as=class extends wo{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}}},en=class extends wo{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 Ir=class{static async runInputGuardrails(e,t,n,r){if(e.length===0)return [];let o=e.map(async i=>{let a=Date.now();try{let l=await i.guardrail_function(t,n,r),c={guardrail:i,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new is(c);return c}catch(l){if(l instanceof is)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()-a};throw new is(c)}});return await Promise.all(o)}static async runOutputGuardrails(e,t,n,r){if(e.length===0)return [];let o=e.map(async i=>{let a=Date.now();try{let l=await i.guardrail_function(t,n,r),c={guardrail:i,agent_output:r,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new as(c);return c}catch(l){if(l instanceof as)throw l;let c={guardrail:i,agent_output:r,output:{tripwire_triggered:true,output_info:{error:l instanceof Error?l.message:String(l),reason:"Guardrail execution failed"}},execution_time_ms:Date.now()-a};throw new as(c)}});return await Promise.all(o)}static async runToolInputGuardrails(e,t){let n=[];for(let r of e){let o=Date.now();try{let i=await r.guardrail_function(t),a={guardrail:r,output:i,execution_time_ms:Date.now()-o};if(n.push(a),i.behavior.type==="raise_exception")throw new en(a);if(i.behavior.type==="reject_content")return {results:n,should_execute:!1,rejection_message:i.behavior.message}}catch(i){if(i instanceof en)throw i;let a={guardrail:r,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-o};throw new en(a)}}return {results:n,should_execute:true}}static async runToolOutputGuardrails(e,t){let n=[];for(let r of e){let o=Date.now();try{let i=await r.guardrail_function(t),a={guardrail:r,output:i,execution_time_ms:Date.now()-o};if(n.push(a),i.behavior.type==="raise_exception")throw new en(a);if(i.behavior.type==="reject_content")return {results:n,should_use_output:!1,replacement_message:i.behavior.message}}catch(i){if(i instanceof en)throw i;let a={guardrail:r,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-o};throw new en(a)}}return {results:n,should_use_output:true}}};var Og=null,$g=false;function ko(){if(!$g&&($g=true,typeof process<"u"&&process.env&&!process.env.NEOX_UI_MODE))try{Promise.resolve().then(()=>(Z(),Gi)).then(s=>{Og=s.cliLogger;}).catch(()=>{});}catch{}return Og}var Bg=new WeakMap,hu=null;function Fg(){return {writtenFiles:new Map,editedFiles:new Map,editDetails:new Map,fileReadCache:new Map,toolCallHistory:[],createdAt:Date.now()}}function Ug(s){if(s){let e=Bg.get(s);return e?process.env.CLI_DEBUG==="1"&&ko()?.debug("SESSION",`Retrieved EXISTING SessionState for context: ${Object.keys(s).join(",")}, history: ${e.toolCallHistory.length}`):(e=Fg(),Bg.set(s,e),process.env.CLI_DEBUG==="1"&&ko()?.debug("SESSION",`Created NEW SessionState for context: ${Object.keys(s).join(",")}`)),e}return hu||(hu=Fg()),hu}function fu(s,e,t,n){let r=Ug(s);if(process.env.CLI_DEBUG==="1"){let o=ko();o?.debug("SESSION","recordToolCall called:"),o?.debug("SESSION",` - tool: ${e}`),o?.debug("SESSION",` - success: ${n}`),o?.debug("SESSION",` - context exists: ${!!s}`),o?.debug("SESSION",` - context identity: ${s?Object.keys(s).join(","):"none"}`),o?.debug("SESSION",` - history length before: ${r.toolCallHistory.length}`);}r.toolCallHistory.push({name:e,args:t,timestamp:Date.now(),success:n}),process.env.CLI_DEBUG==="1"&&ko()?.debug("SESSION",` - history length after: ${r.toolCallHistory.length}`),r.toolCallHistory.length>100&&r.toolCallHistory.shift();}function jg(s,e=10){let t=Ug(s);if(process.env.CLI_DEBUG==="1"){let n=ko();n?.debug("SESSION","getRecentToolCalls called:"),n?.debug("SESSION",` - context exists: ${!!s}`),n?.debug("SESSION",` - context identity: ${s?Object.keys(s).join(","):"none"}`),n?.debug("SESSION",` - total history length: ${t.toolCallHistory.length}`),n?.debug("SESSION",` - limit: ${e}`),n?.debug("SESSION",` - returning ${Math.min(t.toolCallHistory.length,e)} calls`);}return t.toolCallHistory.slice(-e)}var IT=fileURLToPath(import.meta.url),vu=dirname(IT),Cu=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(vu.includes(".asar")||vu.includes("app.asar")){try{let{app:e}=zg();if(e&&e.getPath){let t=e.getPath("userData");return he__default.join(t,"logs")}}catch{}return he__default.join(gi__default.tmpdir(),"neox-logs")}return he__default.join(vu,"../../logs")}initLogDir(){try{Je__default.existsSync(this.logDir)||Je__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 he__default.join(this.logDir,`${e}-${t}.log`)}write(e,t){if(!this.enabled)return;let n=new Date().toISOString(),r=typeof t=="string"?{message:t}:t||{},o=this.safeStringify({timestamp:n,...r})+`
|
|
214
214
|
`;if(this.enabled)try{let i=this.getLogFile(e);Je__default.appendFileSync(i,o,"utf-8");}catch(i){(i.code==="EACCES"||i.code==="EPERM")&&(this.enabled=false);}}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(n,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return "[Circular]";t.add(r);}return n==="parser"||n==="socket"||n==="_httpMessage"||n==="req"||n==="res"?"[Omitted]":r&&r.type==="Buffer"&&Array.isArray(r.data)?"[Buffer]":typeof r=="function"?"[Function]":r})}llmRequest(e,t,n,r,o){let i=n.tools?.map(a=>({name:a.name,description:a.description,parameters:a.parameters}));this.write("llm",{type:"REQUEST",provider:e,model:t,url:r,headers:o,messagesCount:n.messages?.length||0,messages:n.messages,toolsCount:n.tools?.length||0,tools:i,temperature:n.temperature});}llmResponse(e,t,n,r){this.write("llm",{type:"RESPONSE",provider:e,duration:`${t}ms`,usage:n,finishReason:r.finish_reason,content:r.content,contentLength:r.content?.length||0,toolCallsCount:r.tool_calls?.length||0,toolCalls:r.tool_calls});}llmError(e,t){let n={type:"ERROR",provider:e,error:t.message,status:t.response?.status};if(t.response?.data)try{let r=t.response.data;typeof r=="string"?n.data=r:typeof r=="object"&&(n.data={error:r.error,message:r.message,type:r.type,code:r.code});}catch{n.data="[Could not serialize response data]";}this.write("llm",n);}agentStart(e){this.write("agent",{type:"START",task:e});}agentIteration(e,t){this.write("agent",{type:"ITERATION",iteration:e,action:t});}agentComplete(e,t,n){this.write("agent",{type:"COMPLETE",iterations:e,toolCalls:t,usage:n});}agentError(e){this.write("agent",{type:"ERROR",error:e});}toolCall(e,t){this.write("tool",{type:"CALL",tool:e,args:t});}toolResult(e,t,n,r){this.write("tool",{type:"RESULT",tool:e,success:t,resultLength:n,duration:`${r}ms`});}toolError(e,t){this.write("tool",{type:"ERROR",tool:e,error:t});}},xe=new Cu;function qg(s,e){let t=s||"Unknown error",n=t.toLowerCase(),r=e?.providerName?.trim()||"LLM";if(n.includes("timeout")){let o=Math.round((e?.timeoutMs??12e4)/1e3);return [`\u23F1\uFE0F ${r} \u8BF7\u6C42\u8D85\u65F6 (${o}s)\u3002${r} \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(`
|
|
@@ -425,24 +425,24 @@ readfile(path="src/main.ts", range_start="// BEGIN CONFIG", range_end="// END CO
|
|
|
425
425
|
- \u{1F525} edit_file \u524D\u5FC5\u987B\u5148 readfile(..., for_edit=true) - old_string \u987B\u4ECE\u8F93\u51FA\u7CBE\u786E\u590D\u5236
|
|
426
426
|
- for_edit=true \u4F1A\u5305\u542B COPY \u533A\u5757\uFF08\u8F93\u51FA\u66F4\u5927\uFF09
|
|
427
427
|
- max_output_chars \u53EF\u9650\u5236\u8F93\u51FA\u957F\u5EA6
|
|
428
|
-
- \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: ${Io})`},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: ${Yh})`}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:d,num_lines:m,symbol:g,symbol_kind:h,class_name:f,function:v,class:b,pattern:C,match_index:T,list_matches:w,range_start:E,range_end:N,ranges:D,anchor_lines:$,context:k,use_index:M=true,for_edit:_,max_output_chars:P}=l,j=e(),z=xk(j),A=_===true,O=typeof k=="number"?Math.max(0,k):va,F=typeof P=="number"&&P>0?Math.floor(P):Yh,U=m||(A?bk:Io);U=Math.min(U,Ca),!m&&C&&(U=Math.max(Ga,O*2+1));let K=Array.isArray(D)&&D.length>0,de=Array.isArray($)&&$.length>0,W=w===true;if(A&&(K||de||W))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 H=()=>he.isAbsolute(c)?c:he.resolve(j,c),
|
|
429
|
-
`);return {absPath:ee,lines:q,totalLines:q.length}},J=(ee,ve,L)=>{let q=Math.max(1,Math.floor(ee)),Q=typeof ve=="number"?Math.floor(ve):q+U-1,le=Math.min(L,Math.max(Q,q));return {start:q,end:le}},fe=ee=>{let ve=ee.filter(q=>Number.isFinite(q.start)&&Number.isFinite(q.end)).sort((q,Q)=>q.start-Q.start),L=[];for(let q of ve){let Q=L[L.length-1];!Q||q.start>Q.end+1?L.push({...q}):Q.end=Math.max(Q.end,q.end);}return L};if(W){if(!C)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:ee,lines:ve,totalLines:L}=await
|
|
428
|
+
- \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: ${Io})`},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: ${Yh})`}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:d,num_lines:m,symbol:g,symbol_kind:h,class_name:f,function:v,class:b,pattern:C,match_index:T,list_matches:w,range_start:E,range_end:N,ranges:D,anchor_lines:$,context:k,use_index:M=true,for_edit:_,max_output_chars:P}=l,j=e(),z=xk(j),A=_===true,O=typeof k=="number"?Math.max(0,k):va,F=typeof P=="number"&&P>0?Math.floor(P):Yh,U=m||(A?bk:Io);U=Math.min(U,Ca),!m&&C&&(U=Math.max(Ga,O*2+1));let K=Array.isArray(D)&&D.length>0,de=Array.isArray($)&&$.length>0,W=w===true;if(A&&(K||de||W))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 H=()=>he.isAbsolute(c)?c:he.resolve(j,c),ne=async()=>{let ee=H(),ve=await Se.readFile(ee,"utf-8"),q=hs(ve).split(`
|
|
429
|
+
`);return {absPath:ee,lines:q,totalLines:q.length}},J=(ee,ve,L)=>{let q=Math.max(1,Math.floor(ee)),Q=typeof ve=="number"?Math.floor(ve):q+U-1,le=Math.min(L,Math.max(Q,q));return {start:q,end:le}},fe=ee=>{let ve=ee.filter(q=>Number.isFinite(q.start)&&Number.isFinite(q.end)).sort((q,Q)=>q.start-Q.start),L=[];for(let q of ve){let Q=L[L.length-1];!Q||q.start>Q.end+1?L.push({...q}):Q.end=Math.max(Q.end,q.end);}return L};if(W){if(!C)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:ee,lines:ve,totalLines:L}=await ne(),q;try{q=new RegExp(C,"gi");}catch(Re){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${Re.message}`}let Q=[];ve.forEach((Re,De)=>{q.test(Re)&&Q.push({line:De+1,text:Re}),q.lastIndex=0;});let le=En(ee);if(Q.length===0){let Re=Ct(ve.slice(0,Math.min(50,L)),1);return [`\u2713 \u6587\u4EF6: ${le}`,`\u603B\u884C\u6570: ${L} | \u5339\u914D: 0`,"\u7B56\u7565: grep-list","",`\u672A\u627E\u5230\u5339\u914D: "${C}"`,"","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---",Re].join(`
|
|
430
430
|
`)}let Ee=Ku+12,Pe=Math.max(5,Math.min(Ck,Math.floor(F/Ee))),G=Q.slice(0,Pe),X=G.map(Re=>{let De=Re.text.length>Ku?`${Re.text.slice(0,Ku)}...`:Re.text;return `${String(Re.line).padStart(6)} \u2502 ${De}`}),te=[`\u2713 \u6587\u4EF6: ${le}`,`\u603B\u884C\u6570: ${L} | \u5339\u914D: ${Q.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${X.length}/${Q.length}\uFF09---`,...X];X.length<Q.length&&te.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let Ne=G.slice(0,5).map(Re=>Re.line).join(", ");return te.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${le}", anchor_lines=[${Ne}], num_lines=${Math.min(200,U)})`),te.join(`
|
|
431
|
-
`)}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}}if(K||de)try{let{absPath:ee,lines:ve,totalLines:L}=await
|
|
431
|
+
`)}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}}if(K||de)try{let{absPath:ee,lines:ve,totalLines:L}=await ne(),q=[];if(K)for(let X of D)!X||typeof X.start!="number"||q.push(J(X.start,X.end,L));else if(de){let X=Math.max(1,m||O*2+1);for(let te of $){if(typeof te!="number"||Number.isNaN(te))continue;let Ne=Math.max(1,Math.floor(te-Math.floor(X/2))),Re=Math.min(L,Ne+X-1);q.push({start:Ne,end:Re});}}if(q.length===0)return "\u2717 ranges/anchor_lines \u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8BFB\u53D6";let Q=fe(q),Ee=[`\u2713 \u6587\u4EF6: ${En(ee)}`,`\u603B\u884C\u6570: ${L} | \u533A\u5757: ${Q.length}`,"\u7B56\u7565: batch-range","","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"],Pe=Ee.join(`
|
|
432
432
|
`).length,G=0;for(let[X,te]of Q.entries()){let Ne=Ct(ve.slice(te.start-1,te.end),te.start),De=`${`# \u533A\u5757 ${X+1}: ${te.start}-${te.end}`}
|
|
433
433
|
${Ne}`;if(Pe+De.length+2>F&&G>0)break;Ee.push(De,""),Pe+=De.length+2,G+=1;}return G<Q.length&&Ee.push(`\u26A0\uFE0F \u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4EC5\u663E\u793A\u524D ${G} \u4E2A\u533A\u5757`),Ee.join(`
|
|
434
|
-
`).trimEnd()}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}let V;u?V={type:"line",start:u,end:d}:v?V={type:"function",name:v,className:f}:b?V={type:"class",name:b}:g?V={type:"symbol",name:g,kind:h}:C?V={type:"pattern",regex:C,matchIndex:T,context:O}:E&&N&&(V={type:"range",startPattern:E,endPattern:N});let
|
|
434
|
+
`).trimEnd()}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}let V;u?V={type:"line",start:u,end:d}:v?V={type:"function",name:v,className:f}:b?V={type:"class",name:b}:g?V={type:"symbol",name:g,kind:h}:C?V={type:"pattern",regex:C,matchIndex:T,context:O}:E&&N&&(V={type:"range",startPattern:E,endPattern:N});let re=ee=>{let L=[`\u2713 \u6587\u4EF6: ${En(ee.path)}`,`\u603B\u884C\u6570: ${ee.totalLines} | \u663E\u793A: \u7B2C ${ee.startLine}-${ee.endLine} \u884C`,`\u7B56\u7565: ${ee.strategy}${ee.metadata?.matchedLine?` | \u5339\u914D\u884C: ${ee.metadata.matchedLine}`:""}`];if(ee.metadata?.symbol&&L.push(`\u7B26\u53F7: ${ee.metadata.symbol.name} (${ee.metadata.symbol.kind})`),ee.truncated&&(L.push(""),L.push(`\u26A0\uFE0F \u5185\u5BB9\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528 start_line=${ee.endLine+1} \u7EE7\u7EED\u8BFB\u53D6`)),L.push(""),L.push("--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"),L.push(ee.content),A){let le=ee.content.split(`
|
|
435
435
|
`).map(Ee=>{let Pe=Ee.match(/^\s*\d+\s*│\s?(.*)$/);return Pe?Pe[1]:Ee}).join(`
|
|
436
436
|
`);L.push(""),L.push("--- \u{1F525} COPY THIS FOR edit_file old_string (\u4E0D\u5E26\u884C\u53F7) ---"),L.push(le),L.push("--- END ---");}return L.join(`
|
|
437
|
-
`)},ue=0,
|
|
437
|
+
`)},ue=0,se="",ae=!m;for(;;){let ee=await z.read({path:c,locator:V,mode:"smart",autoFullThreshold:ae?ds:void 0,chunkSize:U,expandContext:O,useIndex:M});if(!ee.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.error}
|
|
438
438
|
|
|
439
439
|
\u{1F4A1} \u63D0\u793A:
|
|
440
440
|
- \u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E
|
|
441
|
-
- \u4F7F\u7528 search_files \u67E5\u627E\u6587\u4EF6`;if(re
|
|
441
|
+
- \u4F7F\u7528 search_files \u67E5\u627E\u6587\u4EF6`;if(se=re(ee),!V&&ee.totalLines>ds&&ee.strategy==="chunk"&&(se+=`
|
|
442
442
|
|
|
443
443
|
\u{1F4A1} \u5EFA\u8BAE:
|
|
444
444
|
- \u4F7F\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
|
|
445
|
-
- \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),ae&&ee.strategy==="full"&&
|
|
445
|
+
- \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),ae&&ee.strategy==="full"&&se.length>F){ae=false;let q=Math.max(.1,Math.min(.9,F/se.length));U=Math.max(Ga,Math.floor(U*q)),ue+=1;continue}if(m||se.length<=F||ue>=vk||U<=Ga)return se;let ve=Math.max(.1,Math.min(.9,F/se.length)),L=Math.max(Ga,Math.floor(U*ve));if(L>=U)return se;U=L,ue+=1;}}},n={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
|
|
446
446
|
|
|
447
447
|
\u26A1 \u7279\u6027:
|
|
448
448
|
- \u89E3\u6790 TypeScript/JavaScript/Python \u4EE3\u7801\u7ED3\u6784
|
|
@@ -808,7 +808,7 @@ Available operations: All tools (auto-approved).`}shouldAutoApprove(){return tr
|
|
|
808
808
|
|
|
809
809
|
\u2026[${n-l.length-c.length} chars truncated, total ${t} lines]\u2026
|
|
810
810
|
|
|
811
|
-
`;return l+d+c}var Ka=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;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 fa(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new Ha,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new ba({debug:process.env.CLI_DEBUG==="1",minRecentMessages:this.minHistoryMessages,enableLLMCompression:true}),this.disableSystemPrompt=e.disableSystemPrompt??false,this.unifiedCompressor.setLLMProvider(this.llmProvider,this.model),e.contextWindow&&this.unifiedCompressor.setContextWindow(e.contextWindow),this.currentMode=e.config.mode??"agent",this.modeStrategy=rd(this.currentMode),this.permissionManager=e.permissionManager??new hr({defaultPermission:"ask"}),this.loopDetector=nf(),this.enablePlanMode=e.enablePlanMode??true,e.approvalHandler){let t=e.approvalHandler;this.permissionManager.setApprovalHandler(async n=>({approved:await t({id:"",name:n.toolName,args:n.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=rd(e),p.info("Runner",`Mode switched to: ${e}`);}getMode(){return this.currentMode}getPermissionManager(){return this.permissionManager}computeMaxInputTokens(e,t,n){if(n&&n>0)return n;let o=e&&e>0?e:19e4,i=.7,a=Math.floor(o*i),l=Math.min(t??of,Math.floor(o*.1)),c=Math.max(2e3,a-l);if(process.env.CLI_DEBUG==="1"||process.env.CLI_DEBUG_CONSOLE==="1"){let u=`[Context] maxInputTokens=${c} (contextWindow=${o}, override=${n}, tailBudget=${t??of}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Nk){for await(let i of e)yield i;return}let n=e[Symbol.asyncIterator](),r=t?new Promise((i,a)=>{t.aborted?a(qa()):t.addEventListener("abort",()=>a(qa()),{once:true});}):null,o=false;for(;;){if(t?.aborted){if(n.return)try{await n.return();}catch{}throw qa()}let i=o?Dk:Rk,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(Pk(o?"idle":"first_chunk",i));},i);});try{let c=await Promise.race(r?[n.next(),l,r]:[n.next(),l]);if(a&&clearTimeout(a),c.done)return;o=!0,yield c.value;}catch(c){if(a&&clearTimeout(a),n.return)try{await n.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&p.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),n=await this.unifiedCompressor.compressHistory(t,this.maxInputTokens,{iteration:e,enableLLMCompression:true});if(n.stats.droppedMessages>0||n.stats.llmCompressedMessages>0){this.memory.setMessages(n.messages);let r=this.compressionMode==="async"?"Async":"Sync",o=(n.originalTokens/1e3).toFixed(1),i=(n.compressedTokens/1e3).toFixed(1),a=(n.savedTokens/1e3).toFixed(1),l=n.originalCount,c=n.compressedCount;p.info("Context",`[${r}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${o}K \u2192 ${c}\u6761/${i}K (\u8282\u7701 ${a}K, \u4E22\u5F03${n.stats.droppedMessages}\u6761, LLM\u538B\u7F29${n.stats.llmCompressedMessages}\u6761)`),n.debugInfo&&n.debugInfo.forEach(u=>p.debug("Context",u));}return n}setCompressionMode(e){this.compressionMode=e,p.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 n=(typeof this.contextInjection=="string"?this.contextInjection:await this.contextInjection(e,{name:this.agentName,description:this.agentDescription}))?.trim();return n||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,n){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(p.debug("MK",` hasSignal: ${!!n}`),p.debug("RUNNER","========================================"),p.debug("RUNNER","=== runner.run ENTRY ==="),p.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),p.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),p.debug("RUNNER",` hasSignal: ${!!n}`)),xe.agentStart(e),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let r=this.createRunContext(e,0),o=this.memory.hasConversationMessages?.()??this.memory.getMessagesForLLM().some(M=>M.role==="user"||M.role==="assistant"),i=!o||this.shouldIncludeLastRun(e);r.userData={...r.userData??{},hasConversation:o,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 Ir.runInputGuardrails(this.inputGuardrails,r,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let a=await this.getInstructions(r),l=await this.getContextInjection(r);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",a?.length||0),console.log("[RUNNER] dynamicInstructions START:",a?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",a?.substring(a.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",a?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",a?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(M=>M.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(),a&&this.memory.add({role:"system",content:a});else if(!u){let M=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:M}),this.memory.add({role:"system",content:a}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let _=await Yu(this.workspacePath);_&&this.memory.add({role:"system",content:_});}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 M=[{type:"text",text:e},...t.map(_=>({type:"image_url",image_url:{url:_,detail:"auto"}}))];this.memory.add({role:"user",content:M});}else this.memory.add({role:"user",content:e});let d=Date.now(),m=0,g="",h=0,f={totalTokens:0,promptTokens:0,completionTokens:0},v=false,b=0,C=null,T=new Map,w=0,E=Wn.streamMaxRetries,N=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:Dg,D=N===0||N===1/0,$=af(this.config.maxToolCalls,Ng),k=af(this.config.maxRuntimeMs,Lg);for(;D||m<N;){if(n?.aborted){C="interrupted",v=true,yield {type:"error",error:"Task interrupted by user."};break}if(k!==null&&Date.now()-d>=k){C="runtime_limit",v=true,yield {type:"error",error:`Reached max runtime (${$t(k)}). Please summarize progress and ask whether to continue.`};break}if($!==null&&h>=$){C="tool_call_limit",v=true,yield {type:"error",error:`Reached max tool calls (${$}). Please summarize progress and ask whether to continue.`};break}m++;let M=null;if(this.maxInputTokens){let P=Bt(this.memory.getMessagesForLLM()),j=this.maxInputTokens*.97;P>j&&(M=await this.applyContextWindow(m));}M&&(M.stats.droppedMessages>0||M.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:M.originalCount,keptMessages:M.messages.length,droppedMessages:M.stats.droppedMessages,compressedMessages:M.stats.llmCompressedMessages,originalTokens:M.originalTokens,finalTokens:M.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:M.stats.llmCompressedMessages>0,timestamp:Date.now()});let _=this.memory.checkContextHealth();if((_.warnings.length>0||_.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:_.totalTokens,toolResultTokens:_.toolResultTokens,toolResultRatio:_.toolResultRatio,messageCount:_.messageCount,toolMessageCount:_.toolMessageCount,warnings:_.warnings,shouldCompress:_.shouldCompress,shouldCleanup:_.shouldCleanup,byType:_.byType},event_type:"context_health"},_.shouldCleanup&&_.byType.ephemeral.count>5)){let P=this.memory.cleanupEphemeral();P>0&&p.info("Runner",`Cleaned ${P} ephemeral messages`);}p.debug("Runner",this.memory.getTokenSummary()),xe.agentIteration(m,"thinking"),yield {type:"iteration_start",iteration:m};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let P=this.memory.getMessagesForLLM();if(p.info("LLM",`Request: model=${this.model}, messages=${P.length}, tools=${this.tools.length}`),p.debug("LLM","Request messages",{messageCount:P.length,lastMessage:P[P.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let H=P.filter(oe=>oe.role==="system");console.log("[RUNNER] System messages count:",H.length);for(let oe=0;oe<H.length;oe++){let J=H[oe].content,fe=typeof J=="string"?J:JSON.stringify(J);console.log(`[RUNNER] System[${oe}] length:`,fe?.length||0),console.log(`[RUNNER] System[${oe}] contains \u534F\u4F5C\u6A21\u5F0F:`,fe?.includes("\u534F\u4F5C\u6A21\u5F0F")||!1),console.log(`[RUNNER] System[${oe}] contains delegate_task:`,fe?.includes("delegate_task")||!1),console.log(`[RUNNER] System[${oe}] preview:`,fe?.substring(0,300)||"");}}let j=this.modeStrategy.filterTools(this.tools);process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`Mode: ${this.currentMode}, Available tools: ${j.length}/${this.tools.length}`);let z=this.llmProvider.chatStreamed(this.memory.getMessagesForLLM(),{model:this.model,tools:j,temperature:this.config.temperature,structuredOutput:this.structuredOutput,maxInputTokens:this.maxInputTokens,disableSystemPrompt:this.disableSystemPrompt,signal:n}),A="",O="",F=[],U=[],K="",de={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let H of this.withStreamWatchdog(z,n)){if(H.type==="stream_retry"){yield H;continue}if(H.type==="stream_recovered"){yield {type:"stream_recovered",attempt:H.attempt,maxRetries:H.maxRetries};continue}yield {type:"raw_response_event",data:H,event_type:H.choices?.[0]?.delta?"response.delta":"response.chunk"};let oe=H.choices?.[0]?.delta;if(H.usage){de={prompt_tokens:H.usage.prompt_tokens||de.prompt_tokens,completion_tokens:H.usage.completion_tokens||de.completion_tokens,total_tokens:H.usage.total_tokens||de.total_tokens,cached_tokens:H.usage.cached_tokens,cache_read_input_tokens:H.usage.cache_read_input_tokens,cache_creation_input_tokens:H.usage.cache_creation_input_tokens,prompt_tokens_details:H.usage.prompt_tokens_details},f={promptTokens:de.prompt_tokens,completionTokens:de.completion_tokens,totalTokens:de.total_tokens};let J=!!H.choices?.[0]?.finish_reason;yield {type:"token_usage",usage:de,is_final:J};}if(oe){if(oe.reasoning_content&&(O+=oe.reasoning_content,yield {type:"reasoning_delta",delta:oe.reasoning_content}),oe.reasoning_complete&&(yield {type:"reasoning_complete"}),oe.content&&(A+=oe.content,g=A,yield {type:"text_delta",delta:oe.content}),oe.tool_calls)for(let J of oe.tool_calls){let fe=J.index;U[fe]||(U[fe]={id:J.id||`call_${Math.floor(Date.now())}_${fe}`,type:"function",function:{name:"",arguments:""}}),J.id&&(U[fe].id=J.id),J.function?.name&&(U[fe].function.name=J.function.name),J.function?.arguments&&(U[fe].function.arguments+=J.function.arguments,yield {type:"tool_call_delta",id:U[fe].id,name:U[fe].function.name,arguments_delta:J.function.arguments}),J.thoughtSignature&&(U[fe].thoughtSignature=J.thoughtSignature);}H.choices?.[0]?.finish_reason&&(K=H.choices[0].finish_reason),H.thinking_blocks&&Array.isArray(H.thinking_blocks)&&(F=H.thinking_blocks.map(J=>({type:J.type,thinking:J.thinking,signature:J.signature,data:J.data})));}}A&&(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 W={role:"assistant",content:(A||"").trimEnd()};if(O&&(W.reasoning_content=O),F.length>0&&(W.thinking_blocks=F),U.length>0&&(W.tool_calls=U.map(H=>({...H,function:{...H.function,arguments:H.function.arguments}}))),this.memory.add(W),process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${U.length}, fullContent.length=${A.length}`),U.length>0){let H=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let L of U){let q=L.function.arguments||"";if(H.test(q)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${L.function.name}`),console.error(`[Runner] Arguments preview: ${q.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:L.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.'},v=!0;break}}if(v)break;if($!==null&&h+U.length>$){C="tool_call_limit",v=!0,yield {type:"error",error:`Tool call budget exceeded (max ${$}, requested ${U.length}). Please summarize progress and ask whether to continue.`};break}if(U.length>1){let L=U.map(Q=>Q.function.name),q=[...new Set(L)];q.length===1&&L.length>1?p.info("RUNNER",`\u{1F504} Parallel calls: ${L.length}x ${q[0]} (different parameters)`):p.info("RUNNER",`\u{1F504} Parallel calls: ${L.join(", ")}`);}for(let L of U){h++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:L.id,name:L.function.name,arguments:L.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:L.id,name:L.function.name};let Q=!1;try{L.function.arguments&&(JSON.parse(L.function.arguments),Q=!0);}catch(le){xe.toolError(L.function.name,`Invalid JSON arguments (${le.message}): ${L.function.arguments.substring(0,200)}...`),console.error(`[Runner] \u26A0\uFE0F Tool ${L.function.name} has invalid JSON arguments`),console.error(`[Runner] Arguments length: ${L.function.arguments.length}`),console.error(`[Runner] First 200 chars: ${L.function.arguments.substring(0,200)}`),console.error(`[Runner] Last 200 chars: ${L.function.arguments.substring(Math.max(0,L.function.arguments.length-200))}`);}yield {type:"tool_call_done",id:L.id,name:L.function.name,arguments:L.function.arguments,success:Q},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:L.id,name:L.function.name,arguments:L.function.arguments},event_type:"response.function_call_arguments.done"};}let oe=new Set,J=null,fe=U.length>1;process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`Processing ${U.length} tool call(s)`,{isParallel:fe,tools:U.map(L=>L.function.name)});for(let L of U){let q={};try{let G=L.function.arguments?.trim()||"";q=G?JSON.parse(G):{};}catch(G){xe.toolError(L.function.name,`Loop detection skipped: invalid JSON (${G.message})`);continue}let Q=this.loopDetector.detect(L.function.name,q);if(this.loopDetector.record(L.function.name,q),Q===0)continue;let le=this.loopDetector.generateIntervention(Q,L.function.name,q);if(this.memory.add({role:"system",content:le.message}),Q===2&&sf(L.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:L.id,name:L.function.name,output:le.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:L.function.name,output:le.message,success:!1},this.memory.addToolResult(L.id,L.function.name,le.message),this.loopDetector.updateLastStatus("error"),oe.add(L.id),le.shouldTerminate){J=le;break}}if(J&&(yield {type:"error",error:J.message},v=!0),v)break;let V=oe.size>0?U.filter(L=>!oe.has(L.id)):U,ne=new Set(this.modeStrategy.filterTools(this.tools).map(L=>L.name)),ue=L=>L.replace(/["\s/>]+$/g,"").trim(),re=[];for(let L of V){let q=ue(L.function.name);if(ne.has(q)||ne.has(L.function.name)){re.push(L);continue}let Q=`Tool "${L.function.name}" is not allowed in ${this.currentMode} mode`;xe.toolError(L.function.name,Q),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:L.id,name:L.function.name,output:Q,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:L.function.name,output:Q,success:!1},this.memory.addToolResult(L.id,L.function.name,Q),p.info("PERMISSION",`Tool blocked by mode: ${L.function.name} - ${Q}`);}if(re.length===0)continue;let ae=re.map(L=>({id:L.id,type:"function",function:{name:L.function.name,arguments:L.function.arguments}})),ee=!1;if(process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${ae.length}`),!this.modeStrategy.shouldAutoApprove()){let L=new Set;try{for(let q of re)try{let Q=q.function.arguments.trim(),le=Q?JSON.parse(Q):{},Ee=this.tools.find(G=>G.name===q.function.name);if(!Ee){p.warn("RUNNER",`Tool not found: ${q.function.name}`);continue}let Pe=await lf(n,async()=>this.permissionManager.checkPermission(Ee,le));if(!Pe.allowed){L.add(q.id);let G=Pe.reason||`Tool "${q.function.name}" was denied`;xe.toolError(q.function.name,G),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:q.id,name:q.function.name,output:G,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:q.function.name,output:G,success:!1};let te=JSON.stringify({type:"ephemeral",status:"error",tool:q.function.name,summary:"Tool execution denied by user",error:G,final:!0});this.memory.addToolResult(q.id,q.function.name,te),p.info("PERMISSION",`Tool denied: ${q.function.name} - ${G}`),ee=!0;}}catch(Q){if(Q?.name==="AbortError"||Q?.code==="ERR_CANCELED")throw Q;xe.toolError(q.function.name,Q?.message||"permission check failed");}}catch(q){if(q?.name==="AbortError"||q?.code==="ERR_CANCELED"){p.info("RUNNER","Interrupt detected during permission check"),v=!0;break}throw q}if(re=re.filter(q=>!L.has(q.id)),ae=ae.filter(q=>!L.has(q.id)),ee){p.info("RUNNER","User denied tool - terminating current turn");break}if(ae.length===0)continue}if(process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${ae.length}, userDeniedTool=${ee}`),this.toolInputGuardrails.length>0){let L=new Set;try{for(let q of re)try{let Q=q.function.arguments.trim(),le=Q?JSON.parse(Q):{},Ee={tool_name:q.function.name,tool_input:le,tool_call_id:q.id},Pe=this.tools.find(X=>X.name===q.function.name);if(!Pe)continue;this.runContext.iteration=m;let G=await lf(n,async()=>Ir.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:Ee,agent_name:this.agentName,tool:Pe}));if(!G.should_execute){L.add(q.id);let X=G.rejection_message||`Tool ${q.function.name} was blocked by guardrail`;xe.toolError(q.function.name,`Blocked by guardrail: ${X}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:q.id,name:q.function.name,output:X,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:q.function.name,output:X,success:!1},this.memory.addToolResult(q.id,q.function.name,X),fu(this.runContext,q.function.name,le,!1);}}catch(Q){if(Q?.name==="AbortError"||Q?.code==="ERR_CANCELED")throw Q;if(Q instanceof en){xe.toolError(q.function.name,`Guardrail tripwire triggered: ${Q.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${q.function.name}: ${Q.message}`},v=!0;break}xe.toolError(q.function.name,`Guardrail check failed: ${Q?.message}`);}}catch(q){if(q?.name==="AbortError"||q?.code==="ERR_CANCELED"){p.info("RUNNER","Interrupt detected during guardrails check"),v=!0;break}throw q}if(v)break;if(re=re.filter(q=>!L.has(q.id)),ae=ae.filter(q=>!L.has(q.id)),ae.length===0)continue}process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${ae.length}`);let ve=await this.parallelExecutor.execute(ae,this.tools,L=>{if(xe.toolCall(L.name,{}),L.success){let Q=typeof L.output=="string"?L.output.length:JSON.stringify(L.output).length;xe.toolResult(L.name,!0,Q,L.executionTime||0);}else xe.toolError(L.name,L.output);let q={type:"tool_call_output_item",id:L.id,name:L.name,output:L.output,success:L.success,timestamp:Date.now()};},n);for(let L of ve.results){if(this.toolMetricsHistory.push({name:L.name,duration:L.executionTime||0,success:L.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:L.id,name:L.name,output:L.output,success:L.success,timestamp:Date.now()}},yield {type:"tool_output",name:L.name,output:L.output,success:L.success},L.name==="update_plan"&&L.success)try{p.info("PLAN_UPDATE","\u{1F525} Detected update_plan tool call",{resultId:L.id,toolCallsCount:U.length});let G=U.find(X=>X.id===L.id);if(G){p.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:G.id,argsLength:G.function.arguments?.length});let X=JSON.parse(G.function.arguments||"{}");p.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!X.explanation,planSteps:X.plan?.length}),yield {type:"plan_update",explanation:X.explanation,plan:X.plan,timestamp:Date.now()},p.info("PLAN_UPDATE","\u2705 Emitted plan_update event");}else p.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:L.id,availableIds:U.map(X=>X.id)});}catch(G){p.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:G});}let Q=typeof L.output=="string"?cf(L.output):cf(JSON.stringify(L.output));Q=this.enrichToolResult(Q,L.name,L.executionTime||0);let le=U.find(G=>G.id===L.id),Ee={};if(le)try{Ee=JSON.parse(le.function.arguments||"{}");}catch{}if(this.toolOutputGuardrails.length>0)try{let G=this.tools.find(X=>X.name===L.name);if(G){let X={tool_name:L.name,tool_input:Ee,tool_call_id:L.id},te=await Ir.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:X,agent_name:this.agentName,tool:G,output:L.output});te.should_use_output||(Q=te.replacement_message||"[Output blocked by guardrail]",xe.toolError(L.name,"Output blocked by guardrail"));}}catch(G){G instanceof en&&xe.toolError(L.name,`Output guardrail tripwire triggered: ${G.message}`);}if(!L.success&&typeof L.output=="string"){let G=L.output.toLowerCase();if(G.includes("operation cancelled")||G.includes("command interrupted")||G.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),p.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),v=!0;break}}fu(this.runContext,L.name,Ee,L.success),p.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${L.name}`,{toolName:L.name,success:L.success,rawLength:typeof L.output=="string"?L.output.length:JSON.stringify(L.output).length,truncatedLength:Q.length,outputPreview:Q.substring(0,500)}),this.memory.addToolResult(L.id,L.name,Q);let Pe=L.success?"success":"error";try{let G=typeof L.output=="string"?L.output:JSON.stringify(L.output),X=JSON.parse(G);X.status==="already_done"?Pe="already_done":X.status==="success"?Pe="success":X.status==="error"&&(Pe="error");}catch{}if(this.loopDetector.updateLastStatus(Pe),Pe==="error"){let G=(T.get(L.name)||0)+1;if(T.set(L.name,G),L.name==="edit_file"&&(G===2||G===3)){let X=typeof L.output=="string"?L.output:JSON.stringify(L.output),te=L.name,Ne=tf(te,X);this.memory.add({role:"system",content:Ne});}}else T.set(L.name,0);}if(m>0&&m%5===0){let L=this.buildPerformanceHint();L&&(this.memory.add({role:"system",content:L}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",L));}if(process.env.CLI_DEBUG_CONSOLE==="1"&&ve.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:ve.stats},event_type:"parallel_execution.stats"}),n?.aborted){v=!0;break}continue}else {if(this.plannerMode&&b<2&&this.shouldAutoContinuePlan(A)){b++;let H=this.buildPlanFollowupPrompt();yield {type:"raw_response_event",data:{type:"plan.auto_continue",plan_text:A,followup_prompt:H,count:b},event_type:"plan.auto_continue"},this.memory.add({role:"user",content:H});continue}if(A&&(yield {type:"run_item_stream_event",name:"message_output_created",item:{type:"message_output_item",content:A,role:"assistant",timestamp:Date.now()}}),process.env.CLI_DEBUG==="1"&&(p.info("RUNNER","=== Loop Exit: No Tool Calls ==="),p.info("RUNNER",`Finish Reason: ${K}`),p.info("RUNNER",`Content Length: ${A.length}`),p.info("RUNNER",`Content Preview: ${A.slice(0,300)}`),p.info("RUNNER",`Tool Calls Count: ${U.length}`),p.info("RUNNER",`Iteration: ${m}`)),this.structuredValidator){let H=this.structuredValidator.validate(A);if(H.ok)g=H.normalized||A,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:g,parsed:H.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:H.reason,message:H.message,errors:H.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(H)}),g="";continue}}else g=A;this.outputGuardrails.length>0&&g&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Ir.runOutputGuardrails(this.outputGuardrails,r,this.agentName,g),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});break}}catch(P){if(P?.type==="stream_retry"){yield P;continue}let j=P instanceof Le?P:Zt(P);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:j.category,code:j.code,retryable:j.retryable,message:j.message}),j.category==="canceled"){C="interrupted",v=true,yield {type:"error",error:"Task interrupted by user."};break}if(j.retryable&&w<E){w++;let F=So(j.category,w,j.retryAfter),U=j.category==="retryable_rate_limit",K=j.code==="STREAM_TIMEOUT",de=j.category==="retryable_network"||j.category==="retryable_stream";p.warn("RUNNER",`Retrying after ${$t(F)} (attempt ${w}/${E}): ${j.message}`),yield {type:"raw_response_event",data:{type:"runner.stream_retry",error:j.message,errorCode:j.code,attempt:w,maxRetries:E,delayMs:F,isRateLimit:U,isStreamTimeout:K,isNetworkError:de},event_type:"runner.stream_retry"},await ls(F),m--;continue}let z=ga(j),A=j.message;z&&!A.includes(z)&&(A=`${A}
|
|
811
|
+
`;return l+d+c}var Ka=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;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 fa(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new Ha,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new ba({debug:process.env.CLI_DEBUG==="1",minRecentMessages:this.minHistoryMessages,enableLLMCompression:true}),this.disableSystemPrompt=e.disableSystemPrompt??false,this.unifiedCompressor.setLLMProvider(this.llmProvider,this.model),e.contextWindow&&this.unifiedCompressor.setContextWindow(e.contextWindow),this.currentMode=e.config.mode??"agent",this.modeStrategy=rd(this.currentMode),this.permissionManager=e.permissionManager??new hr({defaultPermission:"ask"}),this.loopDetector=nf(),this.enablePlanMode=e.enablePlanMode??true,e.approvalHandler){let t=e.approvalHandler;this.permissionManager.setApprovalHandler(async n=>({approved:await t({id:"",name:n.toolName,args:n.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=rd(e),p.info("Runner",`Mode switched to: ${e}`);}getMode(){return this.currentMode}getPermissionManager(){return this.permissionManager}computeMaxInputTokens(e,t,n){if(n&&n>0)return n;let o=e&&e>0?e:19e4,i=.7,a=Math.floor(o*i),l=Math.min(t??of,Math.floor(o*.1)),c=Math.max(2e3,a-l);if(process.env.CLI_DEBUG==="1"||process.env.CLI_DEBUG_CONSOLE==="1"){let u=`[Context] maxInputTokens=${c} (contextWindow=${o}, override=${n}, tailBudget=${t??of}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Nk){for await(let i of e)yield i;return}let n=e[Symbol.asyncIterator](),r=t?new Promise((i,a)=>{t.aborted?a(qa()):t.addEventListener("abort",()=>a(qa()),{once:true});}):null,o=false;for(;;){if(t?.aborted){if(n.return)try{await n.return();}catch{}throw qa()}let i=o?Dk:Rk,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(Pk(o?"idle":"first_chunk",i));},i);});try{let c=await Promise.race(r?[n.next(),l,r]:[n.next(),l]);if(a&&clearTimeout(a),c.done)return;o=!0,yield c.value;}catch(c){if(a&&clearTimeout(a),n.return)try{await n.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&p.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),n=await this.unifiedCompressor.compressHistory(t,this.maxInputTokens,{iteration:e,enableLLMCompression:true});if(n.stats.droppedMessages>0||n.stats.llmCompressedMessages>0){this.memory.setMessages(n.messages);let r=this.compressionMode==="async"?"Async":"Sync",o=(n.originalTokens/1e3).toFixed(1),i=(n.compressedTokens/1e3).toFixed(1),a=(n.savedTokens/1e3).toFixed(1),l=n.originalCount,c=n.compressedCount;p.info("Context",`[${r}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${o}K \u2192 ${c}\u6761/${i}K (\u8282\u7701 ${a}K, \u4E22\u5F03${n.stats.droppedMessages}\u6761, LLM\u538B\u7F29${n.stats.llmCompressedMessages}\u6761)`),n.debugInfo&&n.debugInfo.forEach(u=>p.debug("Context",u));}return n}setCompressionMode(e){this.compressionMode=e,p.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 n=(typeof this.contextInjection=="string"?this.contextInjection:await this.contextInjection(e,{name:this.agentName,description:this.agentDescription}))?.trim();return n||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,n){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(p.debug("MK",` hasSignal: ${!!n}`),p.debug("RUNNER","========================================"),p.debug("RUNNER","=== runner.run ENTRY ==="),p.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),p.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),p.debug("RUNNER",` hasSignal: ${!!n}`)),xe.agentStart(e),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let r=this.createRunContext(e,0),o=this.memory.hasConversationMessages?.()??this.memory.getMessagesForLLM().some(M=>M.role==="user"||M.role==="assistant"),i=!o||this.shouldIncludeLastRun(e);r.userData={...r.userData??{},hasConversation:o,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 Ir.runInputGuardrails(this.inputGuardrails,r,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let a=await this.getInstructions(r),l=await this.getContextInjection(r);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",a?.length||0),console.log("[RUNNER] dynamicInstructions START:",a?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",a?.substring(a.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",a?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",a?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(M=>M.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(),a&&this.memory.add({role:"system",content:a});else if(!u){let M=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:M}),this.memory.add({role:"system",content:a}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let _=await Yu(this.workspacePath);_&&this.memory.add({role:"system",content:_});}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 M=[{type:"text",text:e},...t.map(_=>({type:"image_url",image_url:{url:_,detail:"auto"}}))];this.memory.add({role:"user",content:M});}else this.memory.add({role:"user",content:e});let d=Date.now(),m=0,g="",h=0,f={totalTokens:0,promptTokens:0,completionTokens:0},v=false,b=0,C=null,T=new Map,w=0,E=Wn.streamMaxRetries,N=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:Dg,D=N===0||N===1/0,$=af(this.config.maxToolCalls,Ng),k=af(this.config.maxRuntimeMs,Lg);for(;D||m<N;){if(n?.aborted){C="interrupted",v=true,yield {type:"error",error:"Task interrupted by user."};break}if(k!==null&&Date.now()-d>=k){C="runtime_limit",v=true,yield {type:"error",error:`Reached max runtime (${$t(k)}). Please summarize progress and ask whether to continue.`};break}if($!==null&&h>=$){C="tool_call_limit",v=true,yield {type:"error",error:`Reached max tool calls (${$}). Please summarize progress and ask whether to continue.`};break}m++;let M=null;if(this.maxInputTokens){let P=Bt(this.memory.getMessagesForLLM()),j=this.maxInputTokens*.97;P>j&&(M=await this.applyContextWindow(m));}M&&(M.stats.droppedMessages>0||M.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:M.originalCount,keptMessages:M.messages.length,droppedMessages:M.stats.droppedMessages,compressedMessages:M.stats.llmCompressedMessages,originalTokens:M.originalTokens,finalTokens:M.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:M.stats.llmCompressedMessages>0,timestamp:Date.now()});let _=this.memory.checkContextHealth();if((_.warnings.length>0||_.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:_.totalTokens,toolResultTokens:_.toolResultTokens,toolResultRatio:_.toolResultRatio,messageCount:_.messageCount,toolMessageCount:_.toolMessageCount,warnings:_.warnings,shouldCompress:_.shouldCompress,shouldCleanup:_.shouldCleanup,byType:_.byType},event_type:"context_health"},_.shouldCleanup&&_.byType.ephemeral.count>5)){let P=this.memory.cleanupEphemeral();P>0&&p.info("Runner",`Cleaned ${P} ephemeral messages`);}p.debug("Runner",this.memory.getTokenSummary()),xe.agentIteration(m,"thinking"),yield {type:"iteration_start",iteration:m};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let P=this.memory.getMessagesForLLM();if(p.info("LLM",`Request: model=${this.model}, messages=${P.length}, tools=${this.tools.length}`),p.debug("LLM","Request messages",{messageCount:P.length,lastMessage:P[P.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let H=P.filter(ne=>ne.role==="system");console.log("[RUNNER] System messages count:",H.length);for(let ne=0;ne<H.length;ne++){let J=H[ne].content,fe=typeof J=="string"?J:JSON.stringify(J);console.log(`[RUNNER] System[${ne}] length:`,fe?.length||0),console.log(`[RUNNER] System[${ne}] contains \u534F\u4F5C\u6A21\u5F0F:`,fe?.includes("\u534F\u4F5C\u6A21\u5F0F")||!1),console.log(`[RUNNER] System[${ne}] contains delegate_task:`,fe?.includes("delegate_task")||!1),console.log(`[RUNNER] System[${ne}] preview:`,fe?.substring(0,300)||"");}}let j=this.modeStrategy.filterTools(this.tools);process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`Mode: ${this.currentMode}, Available tools: ${j.length}/${this.tools.length}`);let z=this.llmProvider.chatStreamed(this.memory.getMessagesForLLM(),{model:this.model,tools:j,temperature:this.config.temperature,structuredOutput:this.structuredOutput,maxInputTokens:this.maxInputTokens,disableSystemPrompt:this.disableSystemPrompt,signal:n}),A="",O="",F=[],U=[],K="",de={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let H of this.withStreamWatchdog(z,n)){if(H.type==="stream_retry"){yield H;continue}if(H.type==="stream_recovered"){yield {type:"stream_recovered",attempt:H.attempt,maxRetries:H.maxRetries};continue}yield {type:"raw_response_event",data:H,event_type:H.choices?.[0]?.delta?"response.delta":"response.chunk"};let ne=H.choices?.[0]?.delta;if(H.usage){de={prompt_tokens:H.usage.prompt_tokens||de.prompt_tokens,completion_tokens:H.usage.completion_tokens||de.completion_tokens,total_tokens:H.usage.total_tokens||de.total_tokens,cached_tokens:H.usage.cached_tokens,cache_read_input_tokens:H.usage.cache_read_input_tokens,cache_creation_input_tokens:H.usage.cache_creation_input_tokens,prompt_tokens_details:H.usage.prompt_tokens_details},f={promptTokens:de.prompt_tokens,completionTokens:de.completion_tokens,totalTokens:de.total_tokens};let J=!!H.choices?.[0]?.finish_reason;yield {type:"token_usage",usage:de,is_final:J};}if(ne){if(ne.reasoning_content&&(O+=ne.reasoning_content,yield {type:"reasoning_delta",delta:ne.reasoning_content}),ne.reasoning_complete&&(yield {type:"reasoning_complete"}),ne.content&&(A+=ne.content,g=A,yield {type:"text_delta",delta:ne.content}),ne.tool_calls)for(let J of ne.tool_calls){let fe=J.index;U[fe]||(U[fe]={id:J.id||`call_${Math.floor(Date.now())}_${fe}`,type:"function",function:{name:"",arguments:""}}),J.id&&(U[fe].id=J.id),J.function?.name&&(U[fe].function.name=J.function.name),J.function?.arguments&&(U[fe].function.arguments+=J.function.arguments,yield {type:"tool_call_delta",id:U[fe].id,name:U[fe].function.name,arguments_delta:J.function.arguments}),J.thoughtSignature&&(U[fe].thoughtSignature=J.thoughtSignature);}H.choices?.[0]?.finish_reason&&(K=H.choices[0].finish_reason),H.thinking_blocks&&Array.isArray(H.thinking_blocks)&&(F=H.thinking_blocks.map(J=>({type:J.type,thinking:J.thinking,signature:J.signature,data:J.data})));}}A&&(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 W={role:"assistant",content:(A||"").trimEnd()};if(O&&(W.reasoning_content=O),F.length>0&&(W.thinking_blocks=F),U.length>0&&(W.tool_calls=U.map(H=>({...H,function:{...H.function,arguments:H.function.arguments}}))),this.memory.add(W),process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${U.length}, fullContent.length=${A.length}`),U.length>0){let H=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let L of U){let q=L.function.arguments||"";if(H.test(q)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${L.function.name}`),console.error(`[Runner] Arguments preview: ${q.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:L.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.'},v=!0;break}}if(v)break;if($!==null&&h+U.length>$){C="tool_call_limit",v=!0,yield {type:"error",error:`Tool call budget exceeded (max ${$}, requested ${U.length}). Please summarize progress and ask whether to continue.`};break}if(U.length>1){let L=U.map(Q=>Q.function.name),q=[...new Set(L)];q.length===1&&L.length>1?p.info("RUNNER",`\u{1F504} Parallel calls: ${L.length}x ${q[0]} (different parameters)`):p.info("RUNNER",`\u{1F504} Parallel calls: ${L.join(", ")}`);}for(let L of U){h++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:L.id,name:L.function.name,arguments:L.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:L.id,name:L.function.name};let Q=!1;try{L.function.arguments&&(JSON.parse(L.function.arguments),Q=!0);}catch(le){xe.toolError(L.function.name,`Invalid JSON arguments (${le.message}): ${L.function.arguments.substring(0,200)}...`),console.error(`[Runner] \u26A0\uFE0F Tool ${L.function.name} has invalid JSON arguments`),console.error(`[Runner] Arguments length: ${L.function.arguments.length}`),console.error(`[Runner] First 200 chars: ${L.function.arguments.substring(0,200)}`),console.error(`[Runner] Last 200 chars: ${L.function.arguments.substring(Math.max(0,L.function.arguments.length-200))}`);}yield {type:"tool_call_done",id:L.id,name:L.function.name,arguments:L.function.arguments,success:Q},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:L.id,name:L.function.name,arguments:L.function.arguments},event_type:"response.function_call_arguments.done"};}let ne=new Set,J=null,fe=U.length>1;process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`Processing ${U.length} tool call(s)`,{isParallel:fe,tools:U.map(L=>L.function.name)});for(let L of U){let q={};try{let G=L.function.arguments?.trim()||"";q=G?JSON.parse(G):{};}catch(G){xe.toolError(L.function.name,`Loop detection skipped: invalid JSON (${G.message})`);continue}let Q=this.loopDetector.detect(L.function.name,q);if(this.loopDetector.record(L.function.name,q),Q===0)continue;let le=this.loopDetector.generateIntervention(Q,L.function.name,q);if(this.memory.add({role:"system",content:le.message}),Q===2&&sf(L.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:L.id,name:L.function.name,output:le.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:L.function.name,output:le.message,success:!1},this.memory.addToolResult(L.id,L.function.name,le.message),this.loopDetector.updateLastStatus("error"),ne.add(L.id),le.shouldTerminate){J=le;break}}if(J&&(yield {type:"error",error:J.message},v=!0),v)break;let V=ne.size>0?U.filter(L=>!ne.has(L.id)):U,re=new Set(this.modeStrategy.filterTools(this.tools).map(L=>L.name)),ue=L=>L.replace(/["\s/>]+$/g,"").trim(),se=[];for(let L of V){let q=ue(L.function.name);if(re.has(q)||re.has(L.function.name)){se.push(L);continue}let Q=`Tool "${L.function.name}" is not allowed in ${this.currentMode} mode`;xe.toolError(L.function.name,Q),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:L.id,name:L.function.name,output:Q,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:L.function.name,output:Q,success:!1},this.memory.addToolResult(L.id,L.function.name,Q),p.info("PERMISSION",`Tool blocked by mode: ${L.function.name} - ${Q}`);}if(se.length===0)continue;let ae=se.map(L=>({id:L.id,type:"function",function:{name:L.function.name,arguments:L.function.arguments}})),ee=!1;if(process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${ae.length}`),!this.modeStrategy.shouldAutoApprove()){let L=new Set;try{for(let q of se)try{let Q=q.function.arguments.trim(),le=Q?JSON.parse(Q):{},Ee=this.tools.find(G=>G.name===q.function.name);if(!Ee){p.warn("RUNNER",`Tool not found: ${q.function.name}`);continue}let Pe=await lf(n,async()=>this.permissionManager.checkPermission(Ee,le));if(!Pe.allowed){L.add(q.id);let G=Pe.reason||`Tool "${q.function.name}" was denied`;xe.toolError(q.function.name,G),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:q.id,name:q.function.name,output:G,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:q.function.name,output:G,success:!1};let te=JSON.stringify({type:"ephemeral",status:"error",tool:q.function.name,summary:"Tool execution denied by user",error:G,final:!0});this.memory.addToolResult(q.id,q.function.name,te),p.info("PERMISSION",`Tool denied: ${q.function.name} - ${G}`),ee=!0;}}catch(Q){if(Q?.name==="AbortError"||Q?.code==="ERR_CANCELED")throw Q;xe.toolError(q.function.name,Q?.message||"permission check failed");}}catch(q){if(q?.name==="AbortError"||q?.code==="ERR_CANCELED"){p.info("RUNNER","Interrupt detected during permission check"),v=!0;break}throw q}if(se=se.filter(q=>!L.has(q.id)),ae=ae.filter(q=>!L.has(q.id)),ee){p.info("RUNNER","User denied tool - terminating current turn");break}if(ae.length===0)continue}if(process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${ae.length}, userDeniedTool=${ee}`),this.toolInputGuardrails.length>0){let L=new Set;try{for(let q of se)try{let Q=q.function.arguments.trim(),le=Q?JSON.parse(Q):{},Ee={tool_name:q.function.name,tool_input:le,tool_call_id:q.id},Pe=this.tools.find(X=>X.name===q.function.name);if(!Pe)continue;this.runContext.iteration=m;let G=await lf(n,async()=>Ir.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:Ee,agent_name:this.agentName,tool:Pe}));if(!G.should_execute){L.add(q.id);let X=G.rejection_message||`Tool ${q.function.name} was blocked by guardrail`;xe.toolError(q.function.name,`Blocked by guardrail: ${X}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:q.id,name:q.function.name,output:X,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:q.function.name,output:X,success:!1},this.memory.addToolResult(q.id,q.function.name,X),fu(this.runContext,q.function.name,le,!1);}}catch(Q){if(Q?.name==="AbortError"||Q?.code==="ERR_CANCELED")throw Q;if(Q instanceof en){xe.toolError(q.function.name,`Guardrail tripwire triggered: ${Q.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${q.function.name}: ${Q.message}`},v=!0;break}xe.toolError(q.function.name,`Guardrail check failed: ${Q?.message}`);}}catch(q){if(q?.name==="AbortError"||q?.code==="ERR_CANCELED"){p.info("RUNNER","Interrupt detected during guardrails check"),v=!0;break}throw q}if(v)break;if(se=se.filter(q=>!L.has(q.id)),ae=ae.filter(q=>!L.has(q.id)),ae.length===0)continue}process.env.CLI_DEBUG==="1"&&p.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${ae.length}`);let ve=await this.parallelExecutor.execute(ae,this.tools,L=>{if(xe.toolCall(L.name,{}),L.success){let Q=typeof L.output=="string"?L.output.length:JSON.stringify(L.output).length;xe.toolResult(L.name,!0,Q,L.executionTime||0);}else xe.toolError(L.name,L.output);let q={type:"tool_call_output_item",id:L.id,name:L.name,output:L.output,success:L.success,timestamp:Date.now()};},n);for(let L of ve.results){if(this.toolMetricsHistory.push({name:L.name,duration:L.executionTime||0,success:L.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:L.id,name:L.name,output:L.output,success:L.success,timestamp:Date.now()}},yield {type:"tool_output",name:L.name,output:L.output,success:L.success},L.name==="update_plan"&&L.success)try{p.info("PLAN_UPDATE","\u{1F525} Detected update_plan tool call",{resultId:L.id,toolCallsCount:U.length});let G=U.find(X=>X.id===L.id);if(G){p.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:G.id,argsLength:G.function.arguments?.length});let X=JSON.parse(G.function.arguments||"{}");p.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!X.explanation,planSteps:X.plan?.length}),yield {type:"plan_update",explanation:X.explanation,plan:X.plan,timestamp:Date.now()},p.info("PLAN_UPDATE","\u2705 Emitted plan_update event");}else p.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:L.id,availableIds:U.map(X=>X.id)});}catch(G){p.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:G});}let Q=typeof L.output=="string"?cf(L.output):cf(JSON.stringify(L.output));Q=this.enrichToolResult(Q,L.name,L.executionTime||0);let le=U.find(G=>G.id===L.id),Ee={};if(le)try{Ee=JSON.parse(le.function.arguments||"{}");}catch{}if(this.toolOutputGuardrails.length>0)try{let G=this.tools.find(X=>X.name===L.name);if(G){let X={tool_name:L.name,tool_input:Ee,tool_call_id:L.id},te=await Ir.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:X,agent_name:this.agentName,tool:G,output:L.output});te.should_use_output||(Q=te.replacement_message||"[Output blocked by guardrail]",xe.toolError(L.name,"Output blocked by guardrail"));}}catch(G){G instanceof en&&xe.toolError(L.name,`Output guardrail tripwire triggered: ${G.message}`);}if(!L.success&&typeof L.output=="string"){let G=L.output.toLowerCase();if(G.includes("operation cancelled")||G.includes("command interrupted")||G.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),p.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),v=!0;break}}fu(this.runContext,L.name,Ee,L.success),p.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${L.name}`,{toolName:L.name,success:L.success,rawLength:typeof L.output=="string"?L.output.length:JSON.stringify(L.output).length,truncatedLength:Q.length,outputPreview:Q.substring(0,500)}),this.memory.addToolResult(L.id,L.name,Q);let Pe=L.success?"success":"error";try{let G=typeof L.output=="string"?L.output:JSON.stringify(L.output),X=JSON.parse(G);X.status==="already_done"?Pe="already_done":X.status==="success"?Pe="success":X.status==="error"&&(Pe="error");}catch{}if(this.loopDetector.updateLastStatus(Pe),Pe==="error"){let G=(T.get(L.name)||0)+1;if(T.set(L.name,G),L.name==="edit_file"&&(G===2||G===3)){let X=typeof L.output=="string"?L.output:JSON.stringify(L.output),te=L.name,Ne=tf(te,X);this.memory.add({role:"system",content:Ne});}}else T.set(L.name,0);}if(m>0&&m%5===0){let L=this.buildPerformanceHint();L&&(this.memory.add({role:"system",content:L}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",L));}if(process.env.CLI_DEBUG_CONSOLE==="1"&&ve.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:ve.stats},event_type:"parallel_execution.stats"}),n?.aborted){v=!0;break}continue}else {if(this.plannerMode&&b<2&&this.shouldAutoContinuePlan(A)){b++;let H=this.buildPlanFollowupPrompt();yield {type:"raw_response_event",data:{type:"plan.auto_continue",plan_text:A,followup_prompt:H,count:b},event_type:"plan.auto_continue"},this.memory.add({role:"user",content:H});continue}if(A&&(yield {type:"run_item_stream_event",name:"message_output_created",item:{type:"message_output_item",content:A,role:"assistant",timestamp:Date.now()}}),process.env.CLI_DEBUG==="1"&&(p.info("RUNNER","=== Loop Exit: No Tool Calls ==="),p.info("RUNNER",`Finish Reason: ${K}`),p.info("RUNNER",`Content Length: ${A.length}`),p.info("RUNNER",`Content Preview: ${A.slice(0,300)}`),p.info("RUNNER",`Tool Calls Count: ${U.length}`),p.info("RUNNER",`Iteration: ${m}`)),this.structuredValidator){let H=this.structuredValidator.validate(A);if(H.ok)g=H.normalized||A,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:g,parsed:H.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:H.reason,message:H.message,errors:H.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(H)}),g="";continue}}else g=A;this.outputGuardrails.length>0&&g&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Ir.runOutputGuardrails(this.outputGuardrails,r,this.agentName,g),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});break}}catch(P){if(P?.type==="stream_retry"){yield P;continue}let j=P instanceof Le?P:Zt(P);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:j.category,code:j.code,retryable:j.retryable,message:j.message}),j.category==="canceled"){C="interrupted",v=true,yield {type:"error",error:"Task interrupted by user."};break}if(j.retryable&&w<E){w++;let F=So(j.category,w,j.retryAfter),U=j.category==="retryable_rate_limit",K=j.code==="STREAM_TIMEOUT",de=j.category==="retryable_network"||j.category==="retryable_stream";p.warn("RUNNER",`Retrying after ${$t(F)} (attempt ${w}/${E}): ${j.message}`),yield {type:"raw_response_event",data:{type:"runner.stream_retry",error:j.message,errorCode:j.code,attempt:w,maxRetries:E,delayMs:F,isRateLimit:U,isStreamTimeout:K,isNetworkError:de},event_type:"runner.stream_retry"},await ls(F),m--;continue}let z=ga(j),A=j.message;z&&!A.includes(z)&&(A=`${A}
|
|
812
812
|
|
|
813
813
|
\u{1F4A1} Suggestion: ${z}`),v=true;let O=qg(A,{providerName:this.providerName});xe.agentError(O),yield {type:"raw_response_event",data:{type:"error.classified",category:j.category,code:j.code,message:j.message,retryable:j.retryable,suggestion:z,context:j.context},event_type:"error.classified"},yield {type:"error",error:O};break}}!v&&!D&&m>=N&&!g&&(C=C||"iteration_limit",v=true,yield {type:"error",error:`Reached max iterations (${N}). Please summarize progress and ask whether to continue.`}),v||(xe.agentComplete(m,h,f),p.info("LLM",`Complete: iterations=${m}, toolCalls=${h}, tokens=${f.totalTokens} (prompt=${f.promptTokens}, completion=${f.completionTokens})`)),process.env.CLI_DEBUG==="1"&&(p.debug("RUNNER","=== runner.run COMPLETING ==="),p.debug("RUNNER",` iterations: ${m}`),p.debug("RUNNER",` toolCalls: ${h}`),p.debug("RUNNER",` encounteredError: ${v}`),C&&p.debug("RUNNER",` stoppedBy: ${C}`)),yield {type:"run_done"},process.env.CLI_DEBUG==="1"&&p.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 n=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(a=>n.includes(a))?(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."}enrichToolResult(e,t,n){if(n<1e3)return e;let r=n>=1e3?`${(n/1e3).toFixed(1)}s`:`${n}ms`;return `\u23F1\uFE0F [${t} took ${r}]
|
|
814
814
|
|
|
@@ -1032,7 +1032,7 @@ auto_login: { username: "admin", password: "123456" }`,properties:{username:{typ
|
|
|
1032
1032
|
})();
|
|
1033
1033
|
`;(t.collect_console!==false||t.collect_errors!==false)&&(await s.evaluateOnNewDocument(d),s.on("framenavigated",async k=>{if(k===s.mainFrame())try{await k.evaluate(d),p.debug("BROWSER",`Re-injected script after navigation to ${k.url()}`);}catch{}}));let m=await s.createCDPSession();await m.send("Runtime.enable"),await m.send("Log.enable"),t.collect_network!==false&&(o==="cdp"||o==="both")&&(await m.send("Network.enable"),p.debug("BROWSER","Network domain enabled (CDP mode)"));let g=k=>{let{type:M,args:_,timestamp:P}=k,z={log:"log",debug:"debug",info:"info",warning:"warn",error:"error",trace:"trace",assert:"error"}[M]||"log",A=_.map(O=>O.value!==void 0?String(O.value):O.description?O.description:O.preview?.properties?JSON.stringify(O.preview.properties.reduce((F,U)=>(F[U.name]=U.value,F),{})):String(O.type)).join(" ");i.push({type:z,timestamp:P?Math.floor(P):Date.now(),message:A}),p.debug("BROWSER",`[CDP] ${z}: ${A.substring(0,100)}`);},h=k=>{let{exceptionDetails:M}=k,_=M.exception?.description||M.text||"Unknown error";a.push({type:"exception",message:_,stack:M.stackTrace?.callFrames?.map(P=>` at ${P.functionName||"(anonymous)"} (${P.url}:${P.lineNumber}:${P.columnNumber})`).join(`
|
|
1034
1034
|
`)||"",file:M.url,line:M.lineNumber,column:M.columnNumber,timestamp:Date.now()}),p.debug("BROWSER",`[CDP Exception] ${_}`);},f=k=>{let{entry:M}=k,_=M.level;_==="error"?M.text&&(M.text.includes("Uncaught")||M.text.includes("Error"))?(a.push({type:"exception",message:M.text,stack:M.stackTrace?.callFrames?.map(P=>` at ${P.functionName||"(anonymous)"} (${P.url}:${P.lineNumber}:${P.columnNumber})`).join(`
|
|
1035
|
-
`)||"",file:M.url,line:M.lineNumber,timestamp:Date.now()}),p.debug("BROWSER",`[CDP Log Error] ${M.text}`)):(i.push({type:"error",timestamp:Date.now(),message:M.text}),p.debug("BROWSER",`[CDP Log] error: ${M.text}`)):_==="warning"&&i.push({type:"warn",timestamp:Date.now(),message:M.text});};if(t.collect_console!==false&&m.on("Runtime.consoleAPICalled",g),t.collect_errors!==false&&(m.on("Runtime.exceptionThrown",h),m.on("Log.entryAdded",f),s.on("pageerror",k=>{let M=k;a.push({type:"exception",message:M.message,stack:M.stack||"",timestamp:Date.now()}),p.debug("BROWSER",`[Puppeteer pageerror] ${M.message}`);}),s.on("requestfailed",k=>{let M=k.failure();a.push({type:"browser_error",message:`Request failed: ${M?.errorText||"Unknown error"}`,stack:"",file:k.url(),timestamp:Date.now()});})),t.collect_network!==false&&(o==="cdp"||o==="both")&&(m.on("Network.requestWillBeSent",k=>{let M={url:k.request.url,method:k.request.method,resource_type:k.type?.toLowerCase()||"other",request_headers:k.request.headers,timing:{start:k.timestamp*1e3,end:0,duration:0}},_=k.type?.toLowerCase()||"other";if(!(r.xhr_only&&!["xhr","fetch"].includes(_))&&!(!r.xhr_only&&bf.includes(_))){if(k.request.postData){let P=r.body_max_length||5e3,j=k.request.postData;j.length>P?M.request_body=j.substring(0,P)+"...[truncated]":M.request_body=j;}u.set(k.requestId,M),p.debug("BROWSER",`[CDP Network] ${_.toUpperCase()} ${M.method} ${M.url}`);}}),m.on("Network.responseReceived",k=>{let M=u.get(k.requestId);M&&M.timing&&(M.status=k.response.status,M.status_text=k.response.statusText,M.response_headers=k.response.headers,M.timing.end=k.timestamp*1e3,M.timing.duration=M.timing.end-M.timing.start,p.debug("BROWSER",`[CDP Network] Response ${M.status} ${M.url} (${M.timing.duration.toFixed(0)}ms)`));}),m.on("Network.loadingFailed",k=>{let M=u.get(k.requestId);M&&(M.error=k.errorText,M.timing&&(M.timing.end=k.timestamp*1e3,M.timing.duration=M.timing.end-M.timing.start),p.debug("BROWSER",`[CDP Network] Failed ${M.url}: ${M.error}`));})),t.collect_console!==false&&s.on("console",k=>{let M=k.type();i.push({type:M,timestamp:Date.now(),message:k.text(),args:k.args().map(_=>_.toString())}),p.debug("BROWSER",`[Puppeteer console] ${M}: ${k.text().substring(0,100)}`);}),t.collect_network!==false&&(o==="puppeteer"||o==="both")){let k=null;if(r.url_pattern)try{k=new RegExp(r.url_pattern,"i");}catch{p.warn("BROWSER",`Invalid URL pattern: ${r.url_pattern}`);}s.on("request",M=>{let _=M.url(),P=M.resourceType();if(r.xhr_only&&!qk.includes(P)||!r.xhr_only&&bf.includes(P)||k&&!k.test(_))return;`${M.method()}-${_}-${Date.now()}`;let z={url:_,method:M.method(),resource_type:P,request_headers:M.headers(),timing:{start:Date.now(),end:0,duration:0}},A=M.postData();if(A){let O=r.body_max_length||5e3;A.length>O?z.request_body=A.substring(0,O)+"...[truncated]":z.request_body=A;}c.set(_,z),p.debug("BROWSER",`[Network] ${P.toUpperCase()} ${M.method()} ${_}`);}),s.on("response",async M=>{let _=M.url(),P=c.get(_);if(!P||!P.timing)return;P.status=M.status(),P.status_text=M.statusText(),P.response_headers=M.headers(),P.timing.end=Date.now(),P.timing.duration=P.timing.end-P.timing.start;let j=P.status>=400;if(r.include_body&&(j||r.status_filter))try{let A=M.headers()["content-type"]||"";if(A.includes("json")||A.includes("text")||A.includes("html")){let O=await M.text(),F=r.body_max_length||5e3;O.length>F?(P.response_body=O.substring(0,F),P.response_truncated=!0):P.response_body=O;}}catch(A){p.debug("BROWSER",`Failed to get response body for ${_}: ${A}`);}p.debug("BROWSER",`[Network] Response ${P.status} ${_} (${P.timing.duration}ms)`);}),s.on("requestfailed",M=>{let _=M.url(),P=c.get(_),j=M.failure();P&&(P.error=j?.errorText||"Request failed",P.timing&&(P.timing.end=Date.now(),P.timing.duration=P.timing.end-P.timing.start)),a.push({type:"browser_error",message:`Request failed: ${j?.errorText||"Unknown error"}`,stack:"",file:_,timestamp:Date.now()});});}p.info("BROWSER",`Navigating to: ${e}`),await s.goto(e,{waitUntil:"networkidle2",timeout:3e4});try{await m.send("Runtime.enable"),await m.send("Log.enable"),p.debug("BROWSER","Re-enabled Runtime and Log domains after navigation");}catch{p.debug("BROWSER","Failed to re-enable CDP domains (may already be enabled)");}if(t.collect_console!==false||t.collect_errors!==false)try{await s.evaluate(d),p.debug("BROWSER","Ensured script injection after page.goto");}catch{p.debug("BROWSER","Script already injected or page not ready");}let v=t.wait_time||3e3;if(p.info("BROWSER",`Waiting ${v}ms for async content...`),await new Promise(k=>setTimeout(k,v)),p.debug("BROWSER","Starting to extract injected logs..."),t.collect_console!==false||t.collect_errors!==false)try{p.debug("BROWSER","Calling page.evaluate to get __NEOX_CONSOLE_LOGS__...");let k=await s.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));p.debug("BROWSER",`Extracted ${k.consoleLogs.length} console logs and ${k.errors.length} errors from injected script`);for(let P of k.consoleLogs)p.debug("BROWSER",` [${P.type}] ${P.message?.substring(0,100)}`);let M=new Map;for(let P of k.consoleLogs){let j=`${P.type}:${P.message}`;M.has(j)||M.set(j,{type:P.type,timestamp:P.timestamp,message:P.message});}for(let P of i){let j=`${P.type}:${P.message}`;M.has(j)||M.set(j,P);}i.length=0,i.push(...Array.from(M.values()));let _=new Map;for(let P of k.errors){let j=`${P.type}:${P.message}`;_.has(j)||_.set(j,{type:P.type,message:P.message,stack:P.stack||"",file:P.file,line:P.line,column:P.column,timestamp:P.timestamp});}for(let P of a){let j=`${P.type}:${P.message}`;_.has(j)||_.set(j,P);}a.length=0,a.push(...Array.from(_.values())),p.info("BROWSER",`Final: ${i.length} console logs, ${a.length} errors`);}catch(k){p.error("BROWSER","Failed to extract injected logs",{error:k});}let b;if(t.collect_performance!==false)try{let k=await s.metrics(),M=await s.evaluate(()=>{let _=window.performance,P=_.timing,j=_.getEntriesByType("paint"),z=document.querySelectorAll("*"),A=0,O=0,F=0,U=Math.min(1e3,z.length),K=Math.max(1,Math.floor(z.length/U));for(let W=0;W<z.length;W+=K){let H=z[W],oe=window.getComputedStyle(H);oe.display!=="none"&&oe.visibility!=="hidden"&&oe.opacity!=="0"?A++:O++;let J=0,fe=H.parentElement;for(;fe;)J++,fe=fe.parentElement;F=Math.max(F,J);}let de=z.length/U;return A=Math.round(A*de),O=Math.round(O*de),{domContentLoaded:P.domContentLoadedEventEnd-P.navigationStart,loadComplete:P.loadEventEnd-P.navigationStart,paintMetrics:{first_paint:j.find(W=>W.name==="first-paint")?.startTime||0,first_contentful_paint:j.find(W=>W.name==="first-contentful-paint")?.startTime||0},memory:_.memory?{used_heap:_.memory.usedJSHeapSize,total_heap:_.memory.totalJSHeapSize,heap_limit:_.memory.jsHeapSizeLimit}:void 0,domStats:{visible_nodes:A,hidden_nodes:O,max_depth:F}}});b={dom_content_loaded:M.domContentLoaded,load_complete:M.loadComplete,dom_nodes:k.Nodes||0,js_heap_size:k.JSHeapUsedSize||0,event_listeners:k.JSEventListeners||0,paint_metrics:M.paintMetrics,memory:M.memory,dom_stats:M.domStats},p.info("BROWSER",`Performance: ${b.dom_nodes} nodes, ${(b.js_heap_size/1024/1024).toFixed(1)}MB heap`);}catch(k){p.error("BROWSER","Failed to collect performance metrics",{error:k});}let C;if(t.take_screenshot===true)try{C=await s.screenshot({encoding:"base64"});}catch(k){p.error("BROWSER","Failed to capture screenshot",{error:k});}try{await m.detach();}catch{}if(o==="cdp"||o==="both")for(let[k,M]of u.entries())Array.from(c.values()).find(P=>P.url===M.url)||c.set(k,M);let T=Array.from(c.values());o==="cdp"&&(T=Array.from(u.values()));let w=T.length;r.status_filter&&(T=T.filter(k=>Kk(k.status,r.status_filter)));let E=T.filter(k=>k.error||k.status&&k.status>=400).length;T.sort((k,M)=>{let _=k.error||k.status&&k.status>=400,P=M.error||M.status&&M.status>=400;return _&&!P?-1:!_&&P?1:(k.timing?.start||0)-(M.timing?.start||0)});let N=r.max_results||20;T.length>N&&(T=T.slice(0,N));let D={total_captured:w,filtered_count:T.length,error_count:E};p.info("BROWSER",`Network: ${w} captured, ${T.length} returned, ${E} errors`);let $=Date.now()-n;return {console_logs:i,errors:a,network_requests:T,network_stats:D,performance:b,screenshot:C,load_time:$}}function Xa(s){let e=[];s.errors&&s.errors.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${s.errors.length} \u4E2A JavaScript \u5F02\u5E38\uFF1A`),s.errors.slice(0,5).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`),i.file&&e.push(` \u4F4D\u7F6E\uFF1A${i.file}:${i.line||""}`);}),e.push(""));let t=s.console_logs?.filter(i=>i.type==="error")||[];t.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${t.length} \u4E2A console.error \u65E5\u5FD7\uFF1A`),t.slice(0,5).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push(""));let n=s.console_logs?.filter(i=>i.type==="warn")||[];n.length>0&&(e.push(`\u26A0\uFE0F ${n.length} \u4E2A console.warn \u8B66\u544A\uFF1A`),n.slice(0,3).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push(""));let r=s.console_logs?.filter(i=>i.type==="debug")||[];if(r.length>0&&(e.push(`\u{1F50D} ${r.length} \u4E2A console.debug \u65E5\u5FD7\uFF1A`),r.slice(0,3).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push("")),s.errors?.length===0&&t.length===0&&n.length===0&&(e.push("\u2705 \u672A\u53D1\u73B0 JavaScript \u9519\u8BEF\u6216\u8B66\u544A"),e.push("")),s.network_stats){let i=s.network_stats;e.push(`\u{1F310} \u7F51\u7EDC\u8BF7\u6C42\uFF1A\u5171\u6355\u83B7 ${i.total_captured} \u4E2A\uFF0C\u8FD4\u56DE ${i.filtered_count} \u4E2A\uFF0C${i.error_count} \u4E2A\u9519\u8BEF`);}let o=s.network_requests?.filter(i=>i.error||i.status&&i.status>=400)||[];if(o.length>0&&(e.push(`\u{1F534} ${o.length} \u4E2A API \u9519\u8BEF\u8BF7\u6C42\uFF1A`),o.slice(0,5).forEach((i,a)=>{if(e.push(` ${a+1}. [${i.status||"Failed"}] ${i.method} ${i.url}`),i.response_body){let l=i.response_body.substring(0,200);e.push(` \u54CD\u5E94: ${l}${i.response_body.length>200?"...":""}`);}i.error&&e.push(` \u9519\u8BEF: ${i.error}`);}),e.push("")),s.performance){let i=s.performance;if(i.dom_nodes>15e3?e.push(`\u{1F534} \u4E25\u91CD\u8B66\u544A\uFF1ADOM \u8282\u70B9\u8FC7\u591A (${i.dom_nodes.toLocaleString()}), \u9875\u9762\u6027\u80FD\u6781\u5DEE`):i.dom_nodes>1e4?e.push(`\u26A0\uFE0F \u8B66\u544A\uFF1ADOM \u8282\u70B9\u504F\u591A (${i.dom_nodes.toLocaleString()}), \u53EF\u80FD\u5F71\u54CD\u6027\u80FD`):i.dom_nodes>5e3&&e.push(`\u26A1 \u63D0\u793A\uFF1ADOM \u8282\u70B9\u8F83\u591A (${i.dom_nodes.toLocaleString()}), \u5EFA\u8BAE\u4F18\u5316`),i.dom_stats){let a=i.dom_stats,l=a.hidden_nodes/i.dom_nodes*100;e.push(` \u{1F4CA} \u53EF\u89C1: ${a.visible_nodes.toLocaleString()}, \u9690\u85CF: ${a.hidden_nodes.toLocaleString()} (${l.toFixed(1)}%), \u6700\u5927\u6DF1\u5EA6: ${a.max_depth} \u5C42`),l>40&&e.push(" \u26A0\uFE0F \u9690\u85CF\u8282\u70B9\u5360\u6BD4\u8FC7\u9AD8\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6E05\u7406\u7684 DOM \u5143\u7D20"),a.max_depth>30&&e.push(` \u26A0\uFE0F DOM \u5D4C\u5957\u5C42\u7EA7\u8FC7\u6DF1 (${a.max_depth}), \u53EF\u80FD\u5B58\u5728\u6027\u80FD\u95EE\u9898`);}if(i.memory){let a=i.memory.used_heap/1024/1024,l=i.memory.heap_limit/1024/1024,c=i.memory.used_heap/i.memory.heap_limit*100;c>80?e.push(`\u26A1 \u5185\u5B58\u8B66\u544A\uFF1A\u5806\u4F7F\u7528\u7387 ${c.toFixed(1)}% (${a.toFixed(1)}MB / ${l.toFixed(1)}MB), \u63A5\u8FD1\u9650\u5236`):a>100&&e.push(`\u26A1 \u5185\u5B58\u63D0\u793A\uFF1A\u5806\u5185\u5B58\u8F83\u5927 ${a.toFixed(1)}MB`);}else i.js_heap_size>50*1024*1024&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1AJS \u5806\u5185\u5B58\u8FC7\u5927 (${(i.js_heap_size/1024/1024).toFixed(1)}MB)`);i.paint_metrics&&i.paint_metrics.first_contentful_paint>3e3&&e.push(`\u26A1 \u6E32\u67D3\u6162\uFF1A\u9996\u6B21\u5185\u5BB9\u7ED8\u5236 ${i.paint_metrics.first_contentful_paint.toFixed(0)}ms (\u5EFA\u8BAE < 1500ms)`),i.load_complete>5e3&&e.push(`\u26A1 \u52A0\u8F7D\u6162\uFF1A\u9875\u9762\u5B8C\u5168\u52A0\u8F7D\u8017\u65F6 ${i.load_complete.toFixed(0)}ms (\u5EFA\u8BAE < 3000ms)`);}return e.join(`
|
|
1035
|
+
`)||"",file:M.url,line:M.lineNumber,timestamp:Date.now()}),p.debug("BROWSER",`[CDP Log Error] ${M.text}`)):(i.push({type:"error",timestamp:Date.now(),message:M.text}),p.debug("BROWSER",`[CDP Log] error: ${M.text}`)):_==="warning"&&i.push({type:"warn",timestamp:Date.now(),message:M.text});};if(t.collect_console!==false&&m.on("Runtime.consoleAPICalled",g),t.collect_errors!==false&&(m.on("Runtime.exceptionThrown",h),m.on("Log.entryAdded",f),s.on("pageerror",k=>{let M=k;a.push({type:"exception",message:M.message,stack:M.stack||"",timestamp:Date.now()}),p.debug("BROWSER",`[Puppeteer pageerror] ${M.message}`);}),s.on("requestfailed",k=>{let M=k.failure();a.push({type:"browser_error",message:`Request failed: ${M?.errorText||"Unknown error"}`,stack:"",file:k.url(),timestamp:Date.now()});})),t.collect_network!==false&&(o==="cdp"||o==="both")&&(m.on("Network.requestWillBeSent",k=>{let M={url:k.request.url,method:k.request.method,resource_type:k.type?.toLowerCase()||"other",request_headers:k.request.headers,timing:{start:k.timestamp*1e3,end:0,duration:0}},_=k.type?.toLowerCase()||"other";if(!(r.xhr_only&&!["xhr","fetch"].includes(_))&&!(!r.xhr_only&&bf.includes(_))){if(k.request.postData){let P=r.body_max_length||5e3,j=k.request.postData;j.length>P?M.request_body=j.substring(0,P)+"...[truncated]":M.request_body=j;}u.set(k.requestId,M),p.debug("BROWSER",`[CDP Network] ${_.toUpperCase()} ${M.method} ${M.url}`);}}),m.on("Network.responseReceived",k=>{let M=u.get(k.requestId);M&&M.timing&&(M.status=k.response.status,M.status_text=k.response.statusText,M.response_headers=k.response.headers,M.timing.end=k.timestamp*1e3,M.timing.duration=M.timing.end-M.timing.start,p.debug("BROWSER",`[CDP Network] Response ${M.status} ${M.url} (${M.timing.duration.toFixed(0)}ms)`));}),m.on("Network.loadingFailed",k=>{let M=u.get(k.requestId);M&&(M.error=k.errorText,M.timing&&(M.timing.end=k.timestamp*1e3,M.timing.duration=M.timing.end-M.timing.start),p.debug("BROWSER",`[CDP Network] Failed ${M.url}: ${M.error}`));})),t.collect_console!==false&&s.on("console",k=>{let M=k.type();i.push({type:M,timestamp:Date.now(),message:k.text(),args:k.args().map(_=>_.toString())}),p.debug("BROWSER",`[Puppeteer console] ${M}: ${k.text().substring(0,100)}`);}),t.collect_network!==false&&(o==="puppeteer"||o==="both")){let k=null;if(r.url_pattern)try{k=new RegExp(r.url_pattern,"i");}catch{p.warn("BROWSER",`Invalid URL pattern: ${r.url_pattern}`);}s.on("request",M=>{let _=M.url(),P=M.resourceType();if(r.xhr_only&&!qk.includes(P)||!r.xhr_only&&bf.includes(P)||k&&!k.test(_))return;`${M.method()}-${_}-${Date.now()}`;let z={url:_,method:M.method(),resource_type:P,request_headers:M.headers(),timing:{start:Date.now(),end:0,duration:0}},A=M.postData();if(A){let O=r.body_max_length||5e3;A.length>O?z.request_body=A.substring(0,O)+"...[truncated]":z.request_body=A;}c.set(_,z),p.debug("BROWSER",`[Network] ${P.toUpperCase()} ${M.method()} ${_}`);}),s.on("response",async M=>{let _=M.url(),P=c.get(_);if(!P||!P.timing)return;P.status=M.status(),P.status_text=M.statusText(),P.response_headers=M.headers(),P.timing.end=Date.now(),P.timing.duration=P.timing.end-P.timing.start;let j=P.status>=400;if(r.include_body&&(j||r.status_filter))try{let A=M.headers()["content-type"]||"";if(A.includes("json")||A.includes("text")||A.includes("html")){let O=await M.text(),F=r.body_max_length||5e3;O.length>F?(P.response_body=O.substring(0,F),P.response_truncated=!0):P.response_body=O;}}catch(A){p.debug("BROWSER",`Failed to get response body for ${_}: ${A}`);}p.debug("BROWSER",`[Network] Response ${P.status} ${_} (${P.timing.duration}ms)`);}),s.on("requestfailed",M=>{let _=M.url(),P=c.get(_),j=M.failure();P&&(P.error=j?.errorText||"Request failed",P.timing&&(P.timing.end=Date.now(),P.timing.duration=P.timing.end-P.timing.start)),a.push({type:"browser_error",message:`Request failed: ${j?.errorText||"Unknown error"}`,stack:"",file:_,timestamp:Date.now()});});}p.info("BROWSER",`Navigating to: ${e}`),await s.goto(e,{waitUntil:"networkidle2",timeout:3e4});try{await m.send("Runtime.enable"),await m.send("Log.enable"),p.debug("BROWSER","Re-enabled Runtime and Log domains after navigation");}catch{p.debug("BROWSER","Failed to re-enable CDP domains (may already be enabled)");}if(t.collect_console!==false||t.collect_errors!==false)try{await s.evaluate(d),p.debug("BROWSER","Ensured script injection after page.goto");}catch{p.debug("BROWSER","Script already injected or page not ready");}let v=t.wait_time||3e3;if(p.info("BROWSER",`Waiting ${v}ms for async content...`),await new Promise(k=>setTimeout(k,v)),p.debug("BROWSER","Starting to extract injected logs..."),t.collect_console!==false||t.collect_errors!==false)try{p.debug("BROWSER","Calling page.evaluate to get __NEOX_CONSOLE_LOGS__...");let k=await s.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));p.debug("BROWSER",`Extracted ${k.consoleLogs.length} console logs and ${k.errors.length} errors from injected script`);for(let P of k.consoleLogs)p.debug("BROWSER",` [${P.type}] ${P.message?.substring(0,100)}`);let M=new Map;for(let P of k.consoleLogs){let j=`${P.type}:${P.message}`;M.has(j)||M.set(j,{type:P.type,timestamp:P.timestamp,message:P.message});}for(let P of i){let j=`${P.type}:${P.message}`;M.has(j)||M.set(j,P);}i.length=0,i.push(...Array.from(M.values()));let _=new Map;for(let P of k.errors){let j=`${P.type}:${P.message}`;_.has(j)||_.set(j,{type:P.type,message:P.message,stack:P.stack||"",file:P.file,line:P.line,column:P.column,timestamp:P.timestamp});}for(let P of a){let j=`${P.type}:${P.message}`;_.has(j)||_.set(j,P);}a.length=0,a.push(...Array.from(_.values())),p.info("BROWSER",`Final: ${i.length} console logs, ${a.length} errors`);}catch(k){p.error("BROWSER","Failed to extract injected logs",{error:k});}let b;if(t.collect_performance!==false)try{let k=await s.metrics(),M=await s.evaluate(()=>{let _=window.performance,P=_.timing,j=_.getEntriesByType("paint"),z=document.querySelectorAll("*"),A=0,O=0,F=0,U=Math.min(1e3,z.length),K=Math.max(1,Math.floor(z.length/U));for(let W=0;W<z.length;W+=K){let H=z[W],ne=window.getComputedStyle(H);ne.display!=="none"&&ne.visibility!=="hidden"&&ne.opacity!=="0"?A++:O++;let J=0,fe=H.parentElement;for(;fe;)J++,fe=fe.parentElement;F=Math.max(F,J);}let de=z.length/U;return A=Math.round(A*de),O=Math.round(O*de),{domContentLoaded:P.domContentLoadedEventEnd-P.navigationStart,loadComplete:P.loadEventEnd-P.navigationStart,paintMetrics:{first_paint:j.find(W=>W.name==="first-paint")?.startTime||0,first_contentful_paint:j.find(W=>W.name==="first-contentful-paint")?.startTime||0},memory:_.memory?{used_heap:_.memory.usedJSHeapSize,total_heap:_.memory.totalJSHeapSize,heap_limit:_.memory.jsHeapSizeLimit}:void 0,domStats:{visible_nodes:A,hidden_nodes:O,max_depth:F}}});b={dom_content_loaded:M.domContentLoaded,load_complete:M.loadComplete,dom_nodes:k.Nodes||0,js_heap_size:k.JSHeapUsedSize||0,event_listeners:k.JSEventListeners||0,paint_metrics:M.paintMetrics,memory:M.memory,dom_stats:M.domStats},p.info("BROWSER",`Performance: ${b.dom_nodes} nodes, ${(b.js_heap_size/1024/1024).toFixed(1)}MB heap`);}catch(k){p.error("BROWSER","Failed to collect performance metrics",{error:k});}let C;if(t.take_screenshot===true)try{C=await s.screenshot({encoding:"base64"});}catch(k){p.error("BROWSER","Failed to capture screenshot",{error:k});}try{await m.detach();}catch{}if(o==="cdp"||o==="both")for(let[k,M]of u.entries())Array.from(c.values()).find(P=>P.url===M.url)||c.set(k,M);let T=Array.from(c.values());o==="cdp"&&(T=Array.from(u.values()));let w=T.length;r.status_filter&&(T=T.filter(k=>Kk(k.status,r.status_filter)));let E=T.filter(k=>k.error||k.status&&k.status>=400).length;T.sort((k,M)=>{let _=k.error||k.status&&k.status>=400,P=M.error||M.status&&M.status>=400;return _&&!P?-1:!_&&P?1:(k.timing?.start||0)-(M.timing?.start||0)});let N=r.max_results||20;T.length>N&&(T=T.slice(0,N));let D={total_captured:w,filtered_count:T.length,error_count:E};p.info("BROWSER",`Network: ${w} captured, ${T.length} returned, ${E} errors`);let $=Date.now()-n;return {console_logs:i,errors:a,network_requests:T,network_stats:D,performance:b,screenshot:C,load_time:$}}function Xa(s){let e=[];s.errors&&s.errors.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${s.errors.length} \u4E2A JavaScript \u5F02\u5E38\uFF1A`),s.errors.slice(0,5).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`),i.file&&e.push(` \u4F4D\u7F6E\uFF1A${i.file}:${i.line||""}`);}),e.push(""));let t=s.console_logs?.filter(i=>i.type==="error")||[];t.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${t.length} \u4E2A console.error \u65E5\u5FD7\uFF1A`),t.slice(0,5).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push(""));let n=s.console_logs?.filter(i=>i.type==="warn")||[];n.length>0&&(e.push(`\u26A0\uFE0F ${n.length} \u4E2A console.warn \u8B66\u544A\uFF1A`),n.slice(0,3).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push(""));let r=s.console_logs?.filter(i=>i.type==="debug")||[];if(r.length>0&&(e.push(`\u{1F50D} ${r.length} \u4E2A console.debug \u65E5\u5FD7\uFF1A`),r.slice(0,3).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push("")),s.errors?.length===0&&t.length===0&&n.length===0&&(e.push("\u2705 \u672A\u53D1\u73B0 JavaScript \u9519\u8BEF\u6216\u8B66\u544A"),e.push("")),s.network_stats){let i=s.network_stats;e.push(`\u{1F310} \u7F51\u7EDC\u8BF7\u6C42\uFF1A\u5171\u6355\u83B7 ${i.total_captured} \u4E2A\uFF0C\u8FD4\u56DE ${i.filtered_count} \u4E2A\uFF0C${i.error_count} \u4E2A\u9519\u8BEF`);}let o=s.network_requests?.filter(i=>i.error||i.status&&i.status>=400)||[];if(o.length>0&&(e.push(`\u{1F534} ${o.length} \u4E2A API \u9519\u8BEF\u8BF7\u6C42\uFF1A`),o.slice(0,5).forEach((i,a)=>{if(e.push(` ${a+1}. [${i.status||"Failed"}] ${i.method} ${i.url}`),i.response_body){let l=i.response_body.substring(0,200);e.push(` \u54CD\u5E94: ${l}${i.response_body.length>200?"...":""}`);}i.error&&e.push(` \u9519\u8BEF: ${i.error}`);}),e.push("")),s.performance){let i=s.performance;if(i.dom_nodes>15e3?e.push(`\u{1F534} \u4E25\u91CD\u8B66\u544A\uFF1ADOM \u8282\u70B9\u8FC7\u591A (${i.dom_nodes.toLocaleString()}), \u9875\u9762\u6027\u80FD\u6781\u5DEE`):i.dom_nodes>1e4?e.push(`\u26A0\uFE0F \u8B66\u544A\uFF1ADOM \u8282\u70B9\u504F\u591A (${i.dom_nodes.toLocaleString()}), \u53EF\u80FD\u5F71\u54CD\u6027\u80FD`):i.dom_nodes>5e3&&e.push(`\u26A1 \u63D0\u793A\uFF1ADOM \u8282\u70B9\u8F83\u591A (${i.dom_nodes.toLocaleString()}), \u5EFA\u8BAE\u4F18\u5316`),i.dom_stats){let a=i.dom_stats,l=a.hidden_nodes/i.dom_nodes*100;e.push(` \u{1F4CA} \u53EF\u89C1: ${a.visible_nodes.toLocaleString()}, \u9690\u85CF: ${a.hidden_nodes.toLocaleString()} (${l.toFixed(1)}%), \u6700\u5927\u6DF1\u5EA6: ${a.max_depth} \u5C42`),l>40&&e.push(" \u26A0\uFE0F \u9690\u85CF\u8282\u70B9\u5360\u6BD4\u8FC7\u9AD8\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6E05\u7406\u7684 DOM \u5143\u7D20"),a.max_depth>30&&e.push(` \u26A0\uFE0F DOM \u5D4C\u5957\u5C42\u7EA7\u8FC7\u6DF1 (${a.max_depth}), \u53EF\u80FD\u5B58\u5728\u6027\u80FD\u95EE\u9898`);}if(i.memory){let a=i.memory.used_heap/1024/1024,l=i.memory.heap_limit/1024/1024,c=i.memory.used_heap/i.memory.heap_limit*100;c>80?e.push(`\u26A1 \u5185\u5B58\u8B66\u544A\uFF1A\u5806\u4F7F\u7528\u7387 ${c.toFixed(1)}% (${a.toFixed(1)}MB / ${l.toFixed(1)}MB), \u63A5\u8FD1\u9650\u5236`):a>100&&e.push(`\u26A1 \u5185\u5B58\u63D0\u793A\uFF1A\u5806\u5185\u5B58\u8F83\u5927 ${a.toFixed(1)}MB`);}else i.js_heap_size>50*1024*1024&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1AJS \u5806\u5185\u5B58\u8FC7\u5927 (${(i.js_heap_size/1024/1024).toFixed(1)}MB)`);i.paint_metrics&&i.paint_metrics.first_contentful_paint>3e3&&e.push(`\u26A1 \u6E32\u67D3\u6162\uFF1A\u9996\u6B21\u5185\u5BB9\u7ED8\u5236 ${i.paint_metrics.first_contentful_paint.toFixed(0)}ms (\u5EFA\u8BAE < 1500ms)`),i.load_complete>5e3&&e.push(`\u26A1 \u52A0\u8F7D\u6162\uFF1A\u9875\u9762\u5B8C\u5168\u52A0\u8F7D\u8017\u65F6 ${i.load_complete.toFixed(0)}ms (\u5EFA\u8BAE < 3000ms)`);}return e.join(`
|
|
1036
1036
|
`)||"\u2705 \u9875\u9762\u8FD0\u884C\u6B63\u5E38\uFF0C\u672A\u53D1\u73B0\u660E\u663E\u95EE\u9898"}async function vf(s){let e=await Jk(s);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await Vk(s);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let n=await Yk(s);if(n)return {url:`http://localhost:${n}`,port:n,protocol:"http",source:"env"};let r=await Xk(s);return {url:`http://localhost:${r}`,port:r,protocol:"http",source:"default"}}async function Jk(s){try{let e=join(s,"vite.config.js"),n=(await readFile(e,"utf-8")).match(/server\s*:\s*\{[^}]*port\s*:\s*(\d+)/);return n?parseInt(n[1]):null}catch{return null}}async function Vk(s){try{let e=join(s,"package.json"),t=await readFile(e,"utf-8"),r=JSON.parse(t).scripts?.dev||"",o=r.match(/--port\s+(\d+)/);if(o)return parseInt(o[1]);let i=r.match(/PORT=(\d+)/);return i?parseInt(i[1]):null}catch{return null}}async function Yk(s){try{let e=join(s,".env"),n=(await readFile(e,"utf-8")).match(/(?:VITE_)?PORT\s*=\s*(\d+)/);return n?parseInt(n[1]):null}catch{return null}}async function Xk(s){try{let e=join(s,"package.json"),t=await readFile(e,"utf-8"),n=JSON.parse(t),r={...n.dependencies,...n.devDependencies};return r.vite?5173:r.next||r["react-scripts"]?3e3:r.vue?8080:r.nuxt?3e3:r.svelte?5e3:3e3}catch{return 3e3}}async function dd(s,e=3e3){try{let t=new AbortController,n=setTimeout(()=>t.abort(),e),r=await fetch(s,{method:"HEAD",signal:t.signal});return clearTimeout(n),r.ok}catch{return false}}async function pd(s){let e=await vf(s);if(await dd(e.url))return e;let n=[5173,3e3,8080,5e3,4200,8e3];for(let r of n){let o=`http://localhost:${r}`;if(await dd(o))return {url:o,port:r,protocol:"http",source:"default"}}return null}Z();var nS="headers.json";function Cf(s){try{return new URL(s).hostname}catch{return s}}function xf(){let s=Va();return join(s,nS)}function Tf(){let s=xf();if(!existsSync(s))return {};try{let e=readFileSync(s,"utf-8");return JSON.parse(e)}catch(e){return p.warn("HEADERS","Failed to read headers config",{error:e}),{}}}function wf(s){let e=xf();try{let t=JSON.stringify(s,null,2);writeFileSync(e,t,"utf-8"),p.info("HEADERS","Headers config saved",{path:e});}catch(t){p.error("HEADERS","Failed to save headers config",{error:t});}}function el(s,e){let t=Cf(s),n=Tf(),r=rS(e);if(Object.keys(r).length===0){p.info("HEADERS","No headers to save for domain",{domain:t});return}n[t]={headers:r,lastUsed:Date.now(),createdAt:n[t]?.createdAt||Date.now(),url:s},wf(n),p.info("HEADERS","Saved headers for domain",{domain:t,headerCount:Object.keys(r).length});}function md(s){let e=Cf(s),t=Tf(),n=t[e];return n?(n.lastUsed=Date.now(),wf(t),p.info("HEADERS","Retrieved headers for domain",{domain:e,headerCount:Object.keys(n.headers).length}),n.headers):(p.info("HEADERS","No saved headers for domain",{domain:e}),null)}function rS(s){let e={},t=[/^authorization$/i,/^x-/i,/^cookie$/i,/^token$/i,/^auth/i,/^api-key$/i,/^api_key$/i,/^apikey$/i],n=new Set(["user-agent","accept","accept-encoding","accept-language","content-type","content-length","host","origin","referer","connection","cache-control","pragma","upgrade-insecure-requests","sec-fetch-site","sec-fetch-mode","sec-fetch-dest","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform"]);for(let[r,o]of Object.entries(s)){let i=r.toLowerCase();if(n.has(i))continue;t.some(l=>l.test(r))&&(e[r]=o);}return e}var sS=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],oS=['input[type="password"]','form[action*="login"]','form[action*="signin"]','form[action*="auth"]','button[type="submit"]:has-text("\u767B\u5F55")','button[type="submit"]:has-text("Login")','button[type="submit"]:has-text("Sign in")'],iS=['input[name="username"]','input[name="user"]','input[name="email"]','input[name="account"]','input[name="login"]','input[name="userId"]','input[name="loginId"]','input[id="username"]','input[id="user"]','input[id="email"]','input[id="account"]','input[id="login"]','input[type="email"]','input[type="text"][autocomplete="username"]','input[placeholder*="\u7528\u6237\u540D"]','input[placeholder*="\u8D26\u53F7"]','input[placeholder*="\u90AE\u7BB1"]','input[placeholder*="\u624B\u673A"]','input[placeholder*="Username"]','input[placeholder*="Email"]'],aS=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],lS=['button[type="submit"]','input[type="submit"]','button:has-text("\u767B\u5F55")','button:has-text("Login")','button:has-text("Sign in")','button:has-text("Log in")','button:has-text("\u786E\u5B9A")','button:has-text("Submit")','a:has-text("\u767B\u5F55")',".login-btn",".submit-btn","#login-btn","#submit"];async function kf(s,e){let t={},n=false,r=i=>{if(n)return;i.url();let l=i.resourceType();if(l==="xhr"||l==="fetch"||l==="document"){let c=i.headers();Object.assign(t,c);}},o=i=>{if(n)return;let a=i.status();i.url();let c=i.request().resourceType();a>=200&&a<300&&(c==="xhr"||c==="fetch")&&(n=true);};return s.on("request",r),s.on("response",o),t}async function cS(s,e){let t=md(e);return !t||Object.keys(t).length===0?false:(await s.setExtraHTTPHeaders(t),true)}async function gd(s,e){let t=s.url(),n=t.toLowerCase();if(t!==e&&sS.some(o=>n.includes(o)))return {detected:true,original_url:e,redirected_url:t,redirect_type:"url_change",reason:`\u9875\u9762\u88AB\u91CD\u5B9A\u5411\u5230\u767B\u5F55\u9875\u9762: ${t}`};try{for(let r of oS)if(await s.$(r))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"login_form",reason:`\u9875\u9762\u5305\u542B\u767B\u5F55\u8868\u5355\u5143\u7D20: ${r}`}}catch{}try{let r=await s.title(),o=r.toLowerCase(),i=["login","\u767B\u5F55","sign in","\u767B\u5165","authenticate","\u8BA4\u8BC1"];for(let a of i)if(o.includes(a))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"auth_keyword",reason:`\u9875\u9762\u6807\u9898\u5305\u542B\u767B\u5F55\u5173\u952E\u8BCD: "${r}"`}}catch{}return {detected:false,original_url:e}}async function uS(s,e,t){try{t?.("auto_login_start",{message:"\u6B63\u5728\u81EA\u52A8\u586B\u5199\u767B\u5F55\u8868\u5355..."});let n=null;if(e.username_selector&&(n=await s.$(e.username_selector)),!n)for(let i of iS)try{if(n=await s.$(i),n)break}catch{}if(!n)return {success:!1,error:"\u627E\u4E0D\u5230\u7528\u6237\u540D\u8F93\u5165\u6846"};let r=null;if(e.password_selector&&(r=await s.$(e.password_selector)),!r)for(let i of aS)try{if(r=await s.$(i),r)break}catch{}if(!r)return {success:!1,error:"\u627E\u4E0D\u5230\u5BC6\u7801\u8F93\u5165\u6846"};let o=null;if(e.submit_selector&&(o=await s.$(e.submit_selector)),!o)for(let i of lS)try{if(o=await s.$(i),o)break}catch{}return o?(await n.click({clickCount:3}),await n.type(e.username,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u7528\u6237\u540D"}),await r.click({clickCount:3}),await r.type(e.password,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u5BC6\u7801"}),t?.("auto_login_progress",{message:"\u6B63\u5728\u63D0\u4EA4\u767B\u5F55..."}),await Promise.all([s.waitForNavigation({waitUntil:"networkidle0",timeout:3e4}).catch(()=>{}),o.click()]),await new Promise(i=>setTimeout(i,2e3)),{success:!0}):{success:!1,error:"\u627E\u4E0D\u5230\u767B\u5F55\u6309\u94AE"}}catch(n){return {success:false,error:String(n)}}}async function tl(s,e,t){let n=null,o=s.open_for_login===true&&s.allow_manual_login===true,i=s.auto_login&&s.auto_login.username&&s.auto_login.password;try{let a=s.url||"auto";if(a==="auto"){t?.("detecting");let v=await pd(e);if(!v){let b={success:!1,error:"\u672A\u627E\u5230\u8FD0\u884C\u4E2D\u7684\u5F00\u53D1\u670D\u52A1\u5668\u3002\u8BF7\u5148\u542F\u52A8\u5F00\u53D1\u670D\u52A1\u5668\uFF08\u5982 npm run dev\uFF09",url:"",load_time:0,timestamp:Date.now(),summary:"\u9519\u8BEF\uFF1A\u672A\u627E\u5230\u5F00\u53D1\u670D\u52A1\u5668"};return t?.("error",{error:b.error}),b}a=v.url,t?.("detected",{url:a});}t?.("launching",{url:a});let l=o?!1:s.headless!==!1,c=s.use_profile!==!1;n=await ud({headless:l,useProfile:c}),t?.("loading",{url:a});let u=await n.newPage(),d=await cS(u,a);d&&t?.("headers_applied",{message:"\u5DF2\u5E94\u7528\u4FDD\u5B58\u7684\u8BA4\u8BC1 headers"}),await u.goto(a,{waitUntil:"networkidle0",timeout:3e4});let m=await gd(u,a);if(i&&m.detected){t?.("auto_login",{message:"\u68C0\u6D4B\u5230\u767B\u5F55\u9875\u9762\uFF0C\u6B63\u5728\u81EA\u52A8\u767B\u5F55..."});let v=kf(u,a),b=await uS(u,s.auto_login,t);if(!b.success)return await n.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:`\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25: ${b.error}`,login_redirect:m,needs_login:!0};let C=await gd(u,a),T=await v;if(C.detected)return await n.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:"\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u8D26\u53F7\u6216\u5BC6\u7801\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5",login_redirect:C,needs_login:!0};{Object.keys(T).length>0&&(el(a,T),t?.("headers_saved",{headerCount:Object.keys(T).length})),t?.("auto_login_success",{message:"\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F"}),t?.("collecting",{url:a});let w=await Ya(u,a,{wait_time:s.wait_time,collect_console:s.collect_console,collect_errors:s.collect_errors,collect_network:s.collect_network,collect_performance:s.collect_performance,take_screenshot:s.take_screenshot,network_capture_mode:s.network_capture_mode||"cdp",network_filter:{xhr_only:s.network_xhr_only,url_pattern:s.network_url_pattern,status_filter:s.network_status_filter,include_body:s.network_include_body,body_max_length:s.network_body_max_length,max_results:s.network_max_results}}),E=Xa({console_logs:w.console_logs,errors:w.errors,network_requests:w.network_requests,network_stats:w.network_stats,performance:w.performance});return await n.close(),{success:!0,url:a,load_time:w.load_time,timestamp:Date.now(),console_logs:w.console_logs,errors:w.errors,network_requests:w.network_requests,performance:w.performance,screenshot:w.screenshot,summary:`\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F\uFF01
|
|
1037
1037
|
|
|
1038
1038
|
${E}`,login_redirect:{detected:!1,original_url:a},needs_login:!1,captured_headers:T}}}if(m.detected&&!o&&!i)return await n.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:`\u26A0\uFE0F \u9875\u9762\u9700\u8981\u767B\u5F55: ${m.reason}
|
|
@@ -1633,12 +1633,12 @@ search(mode="files", pattern="*.ts") \u2192 \u6587\u4EF6\u540D\u641C\u7D22
|
|
|
1633
1633
|
- \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:s,query:e,keywords:t,queries:n,op:r,mode:o="content",path:i,recursive:a,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:d=2,max_matches:m=200,count_only:g=false},h){try{let f=Date.now();Be.debug("SEARCH",`>>> searchTool.execute START, pattern=${s||e||t?.join(",")}`);let v=h?.signal,b=()=>{if(v?.aborted){let G=new Error("Operation cancelled");throw G.name="AbortError",G}},C=200,T=async()=>{await new Promise(G=>setImmediate(G));},E=ft(i||"."),N="workspace",D=Ft();if(i&&he__default.isAbsolute(i))N="absolute";else if(i&&!Je__default.existsSync(E)){let G=D,X=null;for(;;){let te=he__default.resolve(G,i);if(Je__default.existsSync(te)){X=te;break}let Ne=he__default.dirname(G);if(Ne===G)break;G=Ne;}X&&(E=X,N="ancestor");}let $=rt(E);b();let k;try{k=await Se__default.stat(E);}catch(G){return JSON.stringify(Oe("search","error",`search failed: ${G.message}`,void 0,{error:G.message}))}let M=k.isDirectory(),_=a!==void 0?a:M,P=a_({pattern:s,query:e,keywords:t,queries:n,op:r,case_insensitive:u});if(b(),P.length===0)return JSON.stringify(Oe("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let j=P.filter(G=>G.op!=="not"),z=P.filter(G=>G.op==="and"),A=P.filter(G=>G.op==="or"),O=P.filter(G=>G.op==="not");if(j.length===0)return JSON.stringify(Oe("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let F=P.filter(G=>G.regex).map(G=>{try{return new RegExp(G.pattern),null}catch(X){return `${G.pattern}: ${X.message}`}}).filter(G=>!!G);if(F.length>0)return JSON.stringify(Oe("search","error",`search failed: invalid regex (${F[0]})`,void 0,{error:`Invalid regex: ${F.join("; ")}`}));let U=[];A.length>0&&U.push(A.map(G=>G.pattern).join(" OR ")),z.length>0&&U.push(`AND ${z.map(G=>G.pattern).join(" + ")}`),O.length>0&&U.push(`NOT ${O.map(G=>G.pattern).join(" + ")}`);let K=U.join(" ");Be.debug("SEARCH",`>>> Before isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let de=await i_();Be.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let W=Math.min(200,Math.max(80,d*4+40));if(Be.info("SEARCH",`Strategy: ${de?"ripgrep":"fallback"}`),!de)return JSON.stringify(Oe("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
|
|
1634
1634
|
Please report this issue.`,{error:"ripgrep not available"}));if(b(),o==="files"){let G=await(async()=>{if(!M)return [rt(E)];if(de){let pe=await $d();if(!pe)throw new Error("ripgrep not available (this should not happen)");let _e=["--files"];c&&_e.push("--hidden"),!_&&M&&_e.push("--max-depth","1"),l&&_e.push("-g",l),Od.forEach(Wt=>_e.push("-g",Wt)),_e.push("--",E);let Ot=await wt(pe,_e,Ft(),{signal:v});if(Ot.exitCode!==0&&Ot.exitCode!==1)throw new Error(Ot.stderr||"rg files search failed");return Ot.stdout.split(`
|
|
1635
1635
|
`).filter(Boolean).map(Wt=>{let io=he__default.isAbsolute(Wt)?he__default.resolve(Wt):he__default.resolve(Ft(),Wt);return rt(io)})}let ke=l||"**/*",Y=_?ke:ke.replace("**/","");return (await iy(Y,{cwd:E,absolute:!0,dot:c,onlyFiles:!0,ignore:Od.map(pe=>pe.replace("!",""))})).map(pe=>rt(pe))})();b();let X=P.map(ke=>{let Y=ke.regex?ke.pattern:ey(ke.pattern),me=ke.caseInsensitive?"i":"";return {query:ke,regex:new RegExp(Y,me)}}),te=[],Ne=0;for(let ke of G){b();let Y=ke,me=X.map(He=>({op:He.query.op,hit:He.regex.test(Y)})),pe=me.some(He=>He.op==="or"&&He.hit),_e=me.filter(He=>He.op==="and").every(He=>He.hit);!me.some(He=>He.op==="not"&&He.hit)&&(z.length===0||_e)&&(A.length===0||pe)&&te.push(ke),Ne++,Ne%C===0&&await T();}let Re=[`\u2713 \u6587\u4EF6\u641C\u7D22: ${K}`,`\u25B8 \u8DEF\u5F84: ${$}${_?" (\u9012\u5F52)":""}${N==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",c?"\u25B8 \u5305\u542B\u9690\u85CF\u6587\u4EF6":"","",`\u627E\u5230 ${te.length} \u4E2A\u6587\u4EF6`,""].filter(ke=>ke!==""),De=50;return te.slice(0,De).forEach(ke=>Re.push(` ${ke}`)),te.length>De&&Re.push(` ... \u8FD8\u6709 ${te.length-De} \u4E2A\u6587\u4EF6`),JSON.stringify(Oe("search","success",te.length>0?`search files "${K}" (${te.length} files)`:`search files "${K}" (no matches)`,Re.join(`
|
|
1636
|
-
`),{metadata:{mode:"files",strategy:de?"rg":"glob",regex:P.some(ke=>ke.regex),case_insensitive:u,path:$,resolved_from:N,files:te,queries:P}}))}let H=new Map,
|
|
1636
|
+
`),{metadata:{mode:"files",strategy:de?"rg":"glob",regex:P.some(ke=>ke.regex),case_insensitive:u,path:$,resolved_from:N,files:te,queries:P}}))}let H=new Map,ne=new Map,J=0,fe=O.map(G=>{let X=G.regex?G.pattern:ey(G.pattern),te=G.caseInsensitive?"i":"";return new RegExp(X,te)}),V=[];if(de){let G=await $d();if(!G)throw new Error("ripgrep not available (this should not happen)");for(let X of j){b();let te=["--json","--with-filename","--line-number","--column","-a"];te.push("-C",String(d)),X.caseInsensitive&&te.push("-i"),X.regex||te.push("-F"),c&&te.push("--hidden"),!_&&M&&te.push("--max-depth","1"),l&&te.push("-g",l),Od.forEach(me=>te.push("-g",me)),te.push("--",X.pattern,E);let Ne=`${G} ${te.join(" ")}`;V.push(Ne);let Re="",De=0,ke="";try{let me=await wt(G,te,Ft(),{signal:v});Re=me.stdout,ke=me.stderr||"",De=me.exitCode;}catch(me){if(me?.name==="AbortError"||v?.aborted)throw me;ke=me?.message||me?.stderr||String(me),De=me?.exitCode||2;}if(De!==0&&De!==1){let me=ke?`
|
|
1637
1637
|
Error: ${ke}`:"",pe=`
|
|
1638
1638
|
Command: ${G} ${te.join(" ")}`;throw new Error(`ripgrep failed (exit code ${De})${me}${pe}`)}let Y=0;for(let me of Re.split(`
|
|
1639
|
-
`)){if(b(),Y++,Y%C===0&&await T(),!me.trim())continue;let pe;try{pe=JSON.parse(me);}catch{continue}if(pe.type==="summary"){let Jr=pe.data?.stats;Jr&&typeof Jr.searches=="number"&&(J=Math.max(J,Jr.searches));continue}let _e=pe.type==="match",Ot=pe.type==="context";if(!_e&&!Ot)continue;let He=pe.data,Wt=He?.path?.text,io=He?.line_number,Im=He?.lines?.text,Em=Array.isArray(He?.submatches)?He.submatches[0]:void 0;if(!Wt||!io||typeof Im!="string")continue;let Am=Im.replace(/\n$/,""),Dc=H.get(Wt)||new Map,ao=Dc.get(io)||{line:Am,queryIds:new Set};if(ao.line=Am,_e){ao.queryIds.add(X.id),ao.column===void 0&&Em?.start!==void 0&&(ao.column=Em.start+1);let Jr=
|
|
1639
|
+
`)){if(b(),Y++,Y%C===0&&await T(),!me.trim())continue;let pe;try{pe=JSON.parse(me);}catch{continue}if(pe.type==="summary"){let Jr=pe.data?.stats;Jr&&typeof Jr.searches=="number"&&(J=Math.max(J,Jr.searches));continue}let _e=pe.type==="match",Ot=pe.type==="context";if(!_e&&!Ot)continue;let He=pe.data,Wt=He?.path?.text,io=He?.line_number,Im=He?.lines?.text,Em=Array.isArray(He?.submatches)?He.submatches[0]:void 0;if(!Wt||!io||typeof Im!="string")continue;let Am=Im.replace(/\n$/,""),Dc=H.get(Wt)||new Map,ao=Dc.get(io)||{line:Am,queryIds:new Set};if(ao.line=Am,_e){ao.queryIds.add(X.id),ao.column===void 0&&Em?.start!==void 0&&(ao.column=Em.start+1);let Jr=ne.get(Wt)||new Set;Jr.add(X.id),ne.set(Wt,Jr);}Dc.set(io,ao),H.set(Wt,Dc);}}}let re=new Set(z.map(G=>G.id)),ue=[],se=0,ae=0,ee=0,ve=[],L=[],q=0;for(let[G,X]of H.entries()){if(b(),se>=m&&!g)break;q++,q%C===0&&await T();let te=ne.get(G)||new Set,Ne=!0;if(re.forEach(pe=>{te.has(pe)||(Ne=!1);}),!Ne)continue;let De=Array.from(X.keys()).sort((pe,_e)=>pe-_e).filter(pe=>{let _e=X.get(pe);return _e?!fe.some(Ot=>Ot.test(_e.line)):!1});if(De.length===0)continue;ae++,se+=De.length;let ke=rt(G);if(ve.push({file:ke,anchor_lines:De.slice(0,20),num_lines:W}),g){ue.push({file:G,matches:[],matchCount:De.length});continue}b();let Y=[];Array.from(X.keys()).sort((pe,_e)=>pe-_e).forEach(pe=>{let _e=X.get(pe);if(!_e)return;let Ot=De.includes(pe);if(Y.push({lineNum:pe,line:_e.line,isMatch:Ot}),Ot&&L.length<m){for(let He of _e.queryIds)if(L.push({file:ke,line:pe,column:_e.column,preview:_e.line,queryId:He}),L.length>=m)break}}),ue.push({file:G,matches:Y,matchCount:De.length});}ue.sort((G,X)=>rt(G.file).localeCompare(rt(X.file)));let Q=G=>{let te=rt(G).split(he__default.sep),Ne=te.findIndex(Re=>["src","lib","app","core","packages"].includes(Re));return Ne>=0&&Ne+1<te.length?te[Ne+1]:te[0]||"root"},le=[`\u2713 \u641C\u7D22: ${K}`,`\u25B8 \u8DEF\u5F84: ${$}${_?" (\u9012\u5F52)":""}${N==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",u?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",de?"\u25B8 \u7B56\u7565: ripgrep":"\u25B8 \u7B56\u7565: fallback","","\u2501\u2501\u2501\u2501 \u7ED3\u679C\u6458\u8981 \u2501\u2501\u2501\u2501",J>0?`\u6587\u4EF6: ${J} \u5DF2\u641C\u7D22, ${ae} \u6709\u5339\u914D`:`\u6587\u4EF6: ${ae} \u6709\u5339\u914D`,`\u5339\u914D: ${se}${se>=m?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(G=>G!==""),Ee=new Map,Pe=0;for(let G of ue){Pe++,Pe%C===0&&await T();let X=Q(G.file);Ee.set(X,(Ee.get(X)||0)+G.matchCount);}if(Ee.size>1){le.push(""),le.push("\u{1F4E6} \u6A21\u5757\u5206\u5E03:");let G=Array.from(Ee.entries()).sort((X,te)=>te[1]-X[1]);for(let[X,te]of G.slice(0,5))le.push(` ${X}: ${te}`);G.length>5&&le.push(` ... \u8FD8\u6709 ${G.length-5} \u4E2A\u6A21\u5757`);}if(le.push(""),g){le.push("\u{1F4CB} \u6587\u4EF6\u5217\u8868:");let G=0;for(let X of ue){G++,G%C===0&&await T();let te=rt(X.file),Ne=Q(X.file);le.push(` [${Ne}] ${te}: ${X.matchCount}`);}}else {let G=0,X=100;for(let te of ue){if(b(),ee>=m){le.push(`
|
|
1640
1640
|
... \u8FD8\u6709\u66F4\u591A\u5339\u914D (\u5DF2\u8FBE ${m} \u4E0A\u9650)`);break}let Ne=rt(te.file),Re=Q(te.file);le.push(`
|
|
1641
|
-
\u25B8 [${Re}] ${Ne} (${te.matchCount} \u5904)`),le.push("\u2500".repeat(50));let De=-10;for(let ke of te.matches){if(ee>=m)break;G++,G%X===0&&await T(),ke.lineNum>De+1&&De>0&&le.push(" \u2504\u2504\u2504");let Y=ke.isMatch?"\u25B6":" ";le.push(`${Y}${String(ke.lineNum).padStart(5)} \u2502 ${ke.line}`),De=ke.lineNum,ke.isMatch&&ee++;}}}return ue.length===0?(le.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),le.push(""),le.push("\u{1F4A1} \u5EFA\u8BAE:"),le.push(" - \u5C1D\u8BD5 case_insensitive: true"),le.push(" - \u5C1D\u8BD5 recursive: true \u641C\u7D22\u5B50\u76EE\u5F55"),le.push(" - \u4F7F\u7528 keywords \u6216 queries \u7EC4\u5408\u641C\u7D22"),le.push(' - \u67E5\u6587\u4EF6\u540D\u8BF7\u7528 mode="files"')):ve.length>0&&(le.push(""),le.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),ve.slice(0,3).forEach(G=>{le.push(` readfile(path="${G.file}", anchor_lines=[${G.anchor_lines.join(",")}], num_lines=${G.num_lines})`);})),JSON.stringify(Oe("search","success",ue.length>0?`search "${K}" (${
|
|
1641
|
+
\u25B8 [${Re}] ${Ne} (${te.matchCount} \u5904)`),le.push("\u2500".repeat(50));let De=-10;for(let ke of te.matches){if(ee>=m)break;G++,G%X===0&&await T(),ke.lineNum>De+1&&De>0&&le.push(" \u2504\u2504\u2504");let Y=ke.isMatch?"\u25B6":" ";le.push(`${Y}${String(ke.lineNum).padStart(5)} \u2502 ${ke.line}`),De=ke.lineNum,ke.isMatch&&ee++;}}}return ue.length===0?(le.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),le.push(""),le.push("\u{1F4A1} \u5EFA\u8BAE:"),le.push(" - \u5C1D\u8BD5 case_insensitive: true"),le.push(" - \u5C1D\u8BD5 recursive: true \u641C\u7D22\u5B50\u76EE\u5F55"),le.push(" - \u4F7F\u7528 keywords \u6216 queries \u7EC4\u5408\u641C\u7D22"),le.push(' - \u67E5\u6587\u4EF6\u540D\u8BF7\u7528 mode="files"')):ve.length>0&&(le.push(""),le.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),ve.slice(0,3).forEach(G=>{le.push(` readfile(path="${G.file}", anchor_lines=[${G.anchor_lines.join(",")}], num_lines=${G.num_lines})`);})),JSON.stringify(Oe("search","success",ue.length>0?`search "${K}" (${se} matches)`:`search "${K}" (no matches)`,le.join(`
|
|
1642
1642
|
`),{metadata:{mode:"content",strategy:de?"rg":"fallback",regex:P.some(G=>G.regex),case_insensitive:u,path:$,resolved_from:N,queries:P,matches:L,read_hints:ve,files_with_matches:ae,command:V.length>0?V[0]:void 0}}))}catch(f){return JSON.stringify(Oe("search","error",`search failed: ${f.message}`,void 0,{error:f.message}))}}},c_={name:pl.name,description:pl.description,parameters:pl.parameters,permission:{category:"read",allowInAskMode:true},async function(s){return Qf(s)}},cy=[N0,F0,W0,H0,z0,U0,j0,G0,J0,V0,Y0,X0,Q0,Z0,n_,r_,s_,q0,K0,Lf,o_,l_,id,ad,ld,Gf,c_];async function Ls(s,e){e&&_0(e);let t=e?.capabilities??ht.capabilities,n=nt(),r=[...cy];if(s&&r.push(Wf(s)),n.webSearch?.enabled&&r.push(wd),n.javaDebug?.enabled)try{let c=await Id(n.javaDebug?.jarPath);r.push(...c),Be.info("TOOLS",`Java Debug \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){Be.error("TOOLS",`Java Debug \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`),Be.error("TOOLS","\u63D0\u793A: \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D JAR \u6587\u4EF6");}if(n.smartRead?.enabled!==false)try{let c=Xu(s);r.push(...c),Be.info("TOOLS",`readfile \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){Be.error("TOOLS",`readfile \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`);}let o=typeof process<"u"&&process.type==="renderer";t?.terminal&&o&&r.push(...nl()),t?.editor&&o&&r.push(...rl());let i=E0(r,t),a=n.enabledTools||{};return i.filter(c=>a[c.name]!==false)}yn();var uy=({version:s,provider:e,model:t,workDir:n})=>{let r=(f,v=40)=>{if(f.length<=v)return f;let b=f.split("/");return b.length<=2?f.slice(0,v-3)+"...":"~/"+b.slice(-2).join("/")},o=(f,v=38)=>f.length<=v?f:f.slice(0,v-3)+"...",i=r(n),a=o(t),l=50,c=50,u="#5ba3ff",d=[{c:"#00d9ff",t:" \u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588"},{c:"#00bfff",t:" \u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588"},{c:"#5ba3ff",t:" \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588"},{c:"#9370db",t:" \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588"},{c:"#ff69b4",t:" \u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588"}],m=f=>" ".repeat(Math.max(0,f)),g=(f,v,b,C)=>I.createElement(y,null,I.createElement(y,{color:u},"\u2502"),I.createElement(y,null," "),f,I.createElement(y,null,m(l-1-v)),I.createElement(y,{color:u},"\u2502"),I.createElement(y,null," "),b,I.createElement(y,null,m(c-1-C)),I.createElement(y,{color:u},"\u2502")),h=(f,v)=>I.createElement(y,null,I.createElement(y,{color:u},"\u2502"),I.createElement(y,null," "),f,I.createElement(y,null,m(l-1-v)),I.createElement(y,{color:u},"\u251C","\u2500".repeat(c),"\u2524"));return I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(y,{color:u},"\u256D"+"\u2500".repeat(l)+"\u252C"+"\u2500".repeat(c)+"\u256E"),g(I.createElement(I.Fragment,null,I.createElement(y,{bold:true,color:"cyan"},"Neox"),I.createElement(y,{color:"gray"}," v",s)),6+s.length,I.createElement(y,{color:"yellow",bold:true},"Tips for getting started"),24),g(I.createElement(y,{color:"gray"},"Welcome! Enjoy!"),15,I.createElement(y,null,"Type your message to start"),26),g(I.createElement(y,null," "),1,I.createElement(y,null,"/help or ? for commands"),23),g(I.createElement(y,{color:d[0].c},d[0].t),d[0].t.length,I.createElement(y,null,"Press ? to see all shortcuts"),28),g(I.createElement(y,{color:d[1].c},d[1].t),d[1].t.length,I.createElement(y,null," "),1),h(I.createElement(y,{color:d[2].c},d[2].t),d[2].t.length),g(I.createElement(y,{color:d[3].c},d[3].t),d[3].t.length,I.createElement(y,{color:"blue",bold:true},"What is Neox?"),13),g(I.createElement(y,{color:d[4].c},d[4].t),d[4].t.length,I.createElement(y,null,"Your intelligent coding assistant"),33),g(I.createElement(y,null," "),1,I.createElement(y,null,"Multi-agent collaboration support"),33),g(I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan"},"Provider"),I.createElement(y,null," ",e)),9+e.length,I.createElement(y,null,"Smart context management"),24),g(I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan"},"Model "),I.createElement(y,null," ",a)),9+a.length,I.createElement(y,null," "),1),g(I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan"},"Path "),I.createElement(y,{color:"gray"}," ",i)),9+i.length,I.createElement(y,null," "),1),I.createElement(y,{color:u},"\u2570"+"\u2500".repeat(l)+"\u2534"+"\u2500".repeat(c)+"\u256F"))};function Mt(s){let e=0,t=s.length;for(;e<t&&s[e].trim()==="";)e+=1;for(;t>e&&s[t-1].trim()==="";)t-=1;return s.slice(e,t)}var dy=({message:s,timestamp:e})=>{let t="",n=0;if(typeof s.content=="string")t=s.content;else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"?t+=o.text:o.type==="image_url"&&n++;let r=Mt(t.split(`
|
|
1643
1643
|
`));return I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:"green",bold:true},"\u25B6 You"),n>0&&I.createElement(y,{dimColor:true}," \u{1F4CE} ",n," image",n>1?"s":"")),r.map((o,i)=>I.createElement(S,{key:i},I.createElement(y,{dimColor:true},i===0?"\u2514\u2500 ":" "),I.createElement(y,{wrap:"wrap"},o))))};var py=({message:s,timestamp:e,sourceLabel:t,sourceType:n})=>{let r="";if(typeof s.content=="string")r=s.content;else if(Array.isArray(s.content))for(let l of s.content)l.type==="text"&&(r+=l.text);let o=Mt(r.split(`
|
|
1644
1644
|
`)),i=s.role==="assistant",a=t||"Supervisor";return i?I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:"magenta",bold:true},"\u25CF ",a)),o.map((l,c)=>I.createElement(S,{key:c},I.createElement(y,{dimColor:true},c===0?"\u2514\u2500 ":" "),I.createElement(y,{wrap:"wrap"},l)))):I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:"magenta",bold:true},"\u25B6 ",a)),o.map((l,c)=>I.createElement(S,{key:c},I.createElement(y,{dimColor:true},c===0?"\u2514\u2500 ":" "),I.createElement(y,{wrap:"wrap"},l))))};var Fd=new Marked,bn=markedTerminal({tableOptions:{chars:{top:"\u2500","top-mid":"\u252C","top-left":"\u250C","top-right":"\u2510",bottom:"\u2500","bottom-mid":"\u2534","bottom-left":"\u2514","bottom-right":"\u2518",left:"\u2502","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u253C",right:"\u2502","right-mid":"\u2524",middle:"\u2502"},style:{head:["cyan","bold"],border:["gray"]}},emoji:false,reflowText:false,width:80});bn.renderer.heading;bn.renderer.heading=function(s){let e=s.depth||1,t=s.text||"",n={1:"\x1B[1m\x1B[35m",2:"\x1B[1m\x1B[36m",3:"\x1B[1m\x1B[33m",4:"\x1B[1m\x1B[32m",5:"\x1B[1m\x1B[34m",6:"\x1B[1m\x1B[37m"};return `${n[e]||n[1]}${t}\x1B[0m
|
|
@@ -1680,8 +1680,8 @@ Command: ${G} ${te.join(" ")}`;throw new Error(`ripgrep failed (exit code ${De})
|
|
|
1680
1680
|
`).map((d,m)=>d.trim()?I.createElement(S,{key:m},I.createElement(y,{wrap:"wrap"},d)):null))),e&&I.createElement(S,{marginTop:1,flexDirection:"column"},I.createElement(y,{color:"cyan",bold:true},"\u{1F4DD} \u8BF7\u786E\u8BA4\u662F\u5426\u63A5\u53D7\u6B64\u8BC4\u5BA1\u7ED3\u679C:"),I.createElement(S,{marginLeft:2},I.createElement(y,{dimColor:true},"\u6309 "),I.createElement(y,{color:"green",bold:true},"Y"),I.createElement(y,{dimColor:true}," \u786E\u8BA4\u7EE7\u7EED | \u6309 "),I.createElement(y,{color:"red",bold:true},"N"),I.createElement(y,{dimColor:true}," \u91CD\u65B0\u8BC4\u5BA1 | \u6309 "),I.createElement(y,{color:"yellow",bold:true},"E"),I.createElement(y,{dimColor:true}," \u7F16\u8F91\u9700\u6C42"))))},ky=({data:s})=>{let e=Wd(s.perspective),t=Hd(s.model);return I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:"yellow",bold:true},"\u{1F504} Retry "),I.createElement(y,{color:e.color},e.icon," ",s.agentName),t&&I.createElement(y,{dimColor:true}," (",t,")"),I.createElement(y,{color:"yellow"}," (",s.retryCount,"/",s.maxRetries,")")),I.createElement(S,{marginLeft:2},I.createElement(y,{color:"yellow",wrap:"wrap"},s.error)))},Sy=({data:s})=>{let e=Wd(s.perspective),t=Hd(s.model);return I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:"red",bold:true},"\u2717 Failed "),I.createElement(y,{color:e.color},e.icon," ",s.agentName),t&&I.createElement(y,{dimColor:true}," (",t,")")),I.createElement(S,{marginLeft:2},I.createElement(y,{color:"red"},"\u5DF2\u91CD\u8BD5 ",s.retryCount," \u6B21\uFF0C\u8BE5\u6A21\u578B\u6682\u65F6\u4E0B\u7EBF")),I.createElement(S,{marginLeft:2},I.createElement(y,{color:"red",wrap:"wrap"},s.error)))};var _y=({data:s})=>{let e=Wd(s.perspective),t=Hd(s.model),n={approve:{icon:"\u2713",color:"green",text:"\u540C\u610F"},concern:{icon:"\u25B3",color:"yellow",text:"\u6709\u987E\u8651"},reject:{icon:"\u2717",color:"red",text:"\u62D2\u7EDD"}}[s.verdict],r=useMemo(()=>s.analysis?Ty(s.analysis):"",[s.analysis]);return I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:1},I.createElement(S,{marginBottom:r?1:0},I.createElement(y,{color:e.color,bold:true},e.icon," ",s.agentName),t&&I.createElement(y,{dimColor:true}," (",t,")"),I.createElement(y,{dimColor:true}," \u2192 "),I.createElement(y,{color:n.color,bold:true},n.icon," ",n.text)),r&&I.createElement(S,{flexDirection:"column",marginLeft:2},r.split(`
|
|
1681
1681
|
`).map((o,i)=>o.trim()?I.createElement(S,{key:i},I.createElement(y,{wrap:"wrap"},o)):null)),s.risks&&s.risks.length>0&&I.createElement(S,{flexDirection:"column",marginLeft:2,marginTop:1},I.createElement(y,{color:"yellow",bold:true},"\u26A0\uFE0F \u98CE\u9669"),s.risks.map((o,i)=>I.createElement(S,{key:i,marginLeft:2},I.createElement(y,{color:"yellow"},"\u2022 ",o)))),s.suggestions&&s.suggestions.length>0&&I.createElement(S,{flexDirection:"column",marginLeft:2,marginTop:1},I.createElement(y,{color:"blue",bold:true},"\u{1F4A1} \u5EFA\u8BAE"),s.suggestions.map((o,i)=>I.createElement(S,{key:i,marginLeft:2},I.createElement(y,{dimColor:true},"\u2022 ",o)))))};var M_=s=>{if(s<60)return `${s}\u79D2`;let e=Math.floor(s/60),t=s%60;return t>0?`${e}\u5206${t}\u79D2`:`${e}\u5206\u949F`},Iy=({dag:s})=>{let{nodeCount:e,levelCount:t,maxParallelism:n,criticalPath:r,estimatedTime:o}=s;return I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:"blue",bold:true},"\u2022 \u25C8 DAG \u4EFB\u52A1\u89C4\u5212")),I.createElement(S,null,I.createElement(y,{dimColor:true},"\u251C\u2500 "),I.createElement(y,{color:"white"},"\u8282\u70B9: "),I.createElement(y,{color:"cyan",bold:true},e),I.createElement(y,null," \u2502 "),I.createElement(y,{color:"white"},"\u5C42\u7EA7: "),I.createElement(y,{color:"cyan",bold:true},t),I.createElement(y,null," \u2502 "),I.createElement(y,{color:"white"},"\u6700\u5927\u5E76\u884C: "),I.createElement(y,{color:"cyan",bold:true},n),I.createElement(y,null," \u2502 "),I.createElement(y,{color:"white"},"\u9884\u4F30: "),I.createElement(y,{color:"yellow",bold:true},M_(o))),r.length>0&&I.createElement(S,null,I.createElement(y,{dimColor:true},"\u2514\u2500 "),I.createElement(y,{color:"white",bold:true},"\u5173\u952E\u8DEF\u5F84: "),I.createElement(y,{color:"magenta"},r.slice(0,6).join(" \u2192 "),r.length>6&&` \u2192 ... (${r.length-6} more)`)))};var P_=(s,e)=>{let t={pending:{icon:"\u25CB",color:"gray",text:"\u5F85\u6267\u884C"},ready:{icon:"\u25CE",color:"cyan",text:"\u5C31\u7EEA"},running:{icon:"\u25B6",color:"blue",text:"\u6267\u884C\u4E2D"},completed:{icon:"\u2713",color:"green",text:"\u5B8C\u6210"},failed:{icon:"\u2717",color:"red",text:"\u5931\u8D25"}};return e==="start"?{icon:"\u25B6",color:"blue",text:"\u5F00\u59CB\u6267\u884C"}:e==="complete"?{icon:"\u2713",color:"green",text:"\u6267\u884C\u5B8C\u6210"}:e==="fail"?{icon:"\u2717",color:"red",text:"\u6267\u884C\u5931\u8D25"}:e==="retry"?{icon:"\u{1F504}",color:"yellow",text:"\u91CD\u8BD5\u4E2D"}:t[s]||t.pending},zd=({node:s,eventType:e,progress:t,retryInfo:n})=>{let r=P_(s.status,e),o=t?`Level ${t.level+1}/${t.totalLevels}, ${t.completed}/${t.total} \u5B8C\u6210`:"",i=n?`(\u7B2C ${n.retryCount}/${n.maxRetries} \u6B21\u91CD\u8BD5)`:"";return I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:r.color,bold:true},"\u2022 ",r.icon," ",s.nodeId),I.createElement(y,{color:"gray"}," (",s.role,")"),s.model&&I.createElement(y,{color:"magenta"}," [",s.model,"]"),I.createElement(y,null," - "),I.createElement(y,{color:r.color},r.text),i&&I.createElement(I.Fragment,null,I.createElement(y,{color:"gray"}," "),I.createElement(y,{color:"yellow"},i)),o&&I.createElement(I.Fragment,null,I.createElement(y,{color:"gray"}," | "),I.createElement(y,{color:"cyan"},o))),s.description&&I.createElement(S,null,I.createElement(y,{dimColor:true},"\u251C\u2500 "),I.createElement(y,{wrap:"wrap"},s.description)),e==="retry"&&s.error&&I.createElement(S,null,I.createElement(y,{dimColor:true},"\u2514\u2500 "),I.createElement(y,{color:"yellow"},"\u539F\u56E0: "),I.createElement(y,{color:"yellow",wrap:"wrap"},s.error)),e==="complete"&&s.output&&I.createElement(S,{flexDirection:"column"},I.createElement(S,null,I.createElement(y,{dimColor:true},"\u2514\u2500 "),I.createElement(y,{color:"green"},"\u8F93\u51FA: ")),I.createElement(S,{marginLeft:3,flexDirection:"column"},I.createElement(hl,{content:s.output}))),e==="fail"&&s.error&&I.createElement(S,null,I.createElement(y,{dimColor:true},"\u2514\u2500 "),I.createElement(y,{color:"red"},"\u9519\u8BEF: "),I.createElement(y,{color:"red",wrap:"wrap"},s.error)))};var Ey=({progress:s})=>{let{completed:e,total:t,running:n,failed:r,pending:o,currentLevel:i,totalLevels:a}=s,l=t>0?Math.round(e/t*100):0,c=25,u=Math.floor(e/t*c),d=Math.min(Math.floor(n/t*c),c-u),m=Math.min(Math.floor(r/t*c),c-u-d),g=c-u-d-m;return I.createElement(S,{flexDirection:"column",marginTop:1,marginBottom:0},I.createElement(S,null,I.createElement(y,{color:"blue",bold:true},"\u2022 \u25C8 \u6267\u884C\u8FDB\u5EA6"),I.createElement(y,{color:"gray"}," (Level ",i,"/",a,")")),I.createElement(S,null,I.createElement(y,{dimColor:true},"\u251C\u2500 "),I.createElement(y,{color:"green"},"\u2588".repeat(u)),I.createElement(y,{color:"yellow"},"\u2593".repeat(d)),I.createElement(y,{color:"red"},"\u2592".repeat(m)),I.createElement(y,{color:"gray"},"\u2591".repeat(g)),I.createElement(y,null," "),I.createElement(y,{color:"white",bold:true},l,"%")),I.createElement(S,null,I.createElement(y,{dimColor:true},"\u2514\u2500 "),I.createElement(y,{color:"green"},"\u2713 ",e),I.createElement(y,{color:"gray"}," \u2502 "),I.createElement(y,{color:"yellow"},"\u25B6 ",n),I.createElement(y,{color:"gray"}," \u2502 "),I.createElement(y,{color:"gray"},"\u25CB ",o),r>0&&I.createElement(I.Fragment,null,I.createElement(y,{color:"gray"}," \u2502 "),I.createElement(y,{color:"red"},"\u2717 ",r)),I.createElement(y,{color:"gray"}," / ",t," \u4EFB\u52A1")))};var R_=({entry:s})=>{let e=null;if(s.type==="info"&&s.text)e=I.createElement(Os,{text:s.text,details:s.details,type:"info",timestamp:s.timestamp,sourceLabel:s.sourceLabel});else if(s.type==="warning"&&s.text)e=I.createElement(Os,{text:s.text,details:s.details,type:"warning",timestamp:s.timestamp,sourceLabel:s.sourceLabel});else if(s.type==="error"&&s.text)e=I.createElement(Os,{text:s.text,details:s.details,type:"error",timestamp:s.timestamp,sourceLabel:s.sourceLabel});else if((s.type==="thinking"||s.type==="reasoning")&&s.text)e=I.createElement(gy,{content:s.text,streaming:s.isStreaming,type:s.type,timestamp:s.timestamp,sourceLabel:s.sourceLabel});else if(s.type==="plan"&&s.planSteps){let t={type:"plan_update",explanation:s.planExplanation,plan:s.planSteps,timestamp:s.timestamp.getTime()};e=I.createElement(fy,{event:t,timestamp:s.timestamp,sourceLabel:s.sourceLabel});}else if(s.type==="queued_message"&&s.text)e=I.createElement(Os,{text:s.text,details:s.details,type:"queued_message",timestamp:s.timestamp,sourceLabel:s.sourceLabel});else if(s.type==="supervisor"&&s.message)e=I.createElement(py,{message:s.message,timestamp:s.timestamp,sourceLabel:s.sourceLabel,sourceType:s.sourceType});else if((s.type==="agent_spawn"||s.type==="agent_progress"||s.type==="agent_complete"||s.type==="agent_error")&&s.agentId)e=I.createElement(yy,{agentId:s.agentId,agentIndex:s.agentIndex||1,status:s.agentStatus||"running",task:s.agentTask,progress:s.agentProgress,message:s.text,error:s.agentError,model:s.agentModel,timestamp:s.timestamp,roleId:s.agentRoleId});else if((s.type==="network_decompose"||s.type==="network_task"||s.type==="network_route"||s.type==="network_progress"||s.type==="network_analysis"||s.type==="network_mode_select"||s.type==="network_agent_bid"||s.type==="network_bidding"||s.type==="network_negotiation"||s.type==="network_negotiation_message"||s.type==="network_dag"||s.type==="network_node_start"||s.type==="network_node_complete"||s.type==="network_node_fail"||s.type==="network_replan"||s.type==="network_peer_review")&&s.text)e=I.createElement(by,{type:s.type,text:s.text,details:s.details,timestamp:s.timestamp,networkTaskId:s.networkTaskId,networkRoleId:s.networkRoleId,networkCompleted:s.networkCompleted,networkTotal:s.networkTotal,networkRunning:s.networkRunning,networkFailed:s.networkFailed,networkPending:s.networkPending,isComplete:s.isComplete,networkAnalysis:s.networkAnalysis,networkModeSelect:s.networkModeSelect,networkAgentBid:s.networkAgentBid,networkBidding:s.networkBidding,networkNegotiation:s.networkNegotiation,networkNegotiationMessage:s.networkNegotiationMessage,networkDAG:s.networkDAG,networkNode:s.networkNode,networkReplan:s.networkReplan,networkPeerReview:s.networkPeerReview,sourceLabel:s.sourceLabel});else if((s.type==="collab_spawn"||s.type==="collab_delegate"||s.type==="collab_query"||s.type==="collab_message"||s.type==="collab_wait"||s.type==="collab_terminate")&&s.text)e=I.createElement(vy,{type:s.type,text:s.text,details:s.details,timestamp:s.timestamp,toolName:s.collabToolName,targetAgentId:s.collabTargetAgentId,taskId:s.collabTaskId,result:s.collabResult,sourceLabel:s.sourceLabel});else if(s.type==="pipeline_routing"&&s.pipelineRouting){let n={simple:"\u{1F680} \u7B80\u5355\u8DEF\u5F84 (\u76F4\u63A5\u6267\u884C)",standard:"\u26A1 \u6807\u51C6\u8DEF\u5F84 (CCB + DAG)",complex:"\u{1F52C} \u590D\u6742\u8DEF\u5F84 (\u5B8C\u6574 CCB + \u591A\u9636\u6BB5 DAG)"}[s.pipelineRouting.path]||s.pipelineRouting.path;e=I.createElement(Os,{text:n,details:s.pipelineRouting.reason,type:"info",timestamp:s.timestamp});}else if(s.type==="pipeline_analysis"&&s.pipelineAnalysis)e=I.createElement(Cy,{analysis:s.pipelineAnalysis,timestamp:s.timestamp});else if(s.type==="pipeline_ccb"&&s.pipelineCCB)e=I.createElement(wy,{ccbResult:s.pipelineCCB,timestamp:s.timestamp});else if(s.type==="ccb_review"&&s.ccbReview)e=I.createElement(_y,{data:s.ccbReview,timestamp:s.timestamp});else if(s.type==="ccb_retry"&&s.ccbRetry)e=I.createElement(ky,{data:s.ccbRetry,timestamp:s.timestamp});else if(s.type==="ccb_failed"&&s.ccbFailed)e=I.createElement(Sy,{data:s.ccbFailed,timestamp:s.timestamp});else if(s.type==="pipeline_dag"&&s.pipelineDAG)e=I.createElement(Iy,{dag:s.pipelineDAG,timestamp:s.timestamp});else if((s.type==="pipeline_node_start"||s.type==="pipeline_node_complete"||s.type==="pipeline_node_fail"||s.type==="pipeline_node_retry")&&(s.pipelineNode||s.pipelineNodeRetry)){if(s.type==="pipeline_node_retry"&&s.pipelineNodeRetry){let t=s.pipelineNodeRetry,n=s.pipelineProgress?{level:s.pipelineProgress.currentLevel??0,totalLevels:s.pipelineProgress.totalLevels??1,completed:s.pipelineProgress.completed??0,total:s.pipelineProgress.total??0}:void 0;e=I.createElement(zd,{node:{nodeId:t.nodeId,role:t.role,error:t.error,status:"running"},eventType:"retry",timestamp:s.timestamp,progress:n,retryInfo:{retryCount:t.retryCount,maxRetries:t.maxRetries}});}else if(s.pipelineNode){let t=s.type==="pipeline_node_start"?"start":s.type==="pipeline_node_complete"?"complete":"fail",n=s.pipelineProgress?{level:s.pipelineProgress.currentLevel??0,totalLevels:s.pipelineProgress.totalLevels??1,completed:s.pipelineProgress.completed??0,total:s.pipelineProgress.total??0}:void 0;e=I.createElement(zd,{node:s.pipelineNode,eventType:t,timestamp:s.timestamp,progress:n});}}else s.type==="pipeline_progress"&&s.pipelineProgress?e=I.createElement(Ey,{progress:s.pipelineProgress,timestamp:s.timestamp}):fl[s.type]&&s.text?e=I.createElement(hy,{type:s.type,message:s.text,details:s.details,timestamp:s.timestamp,isStreaming:s.isStreaming,sourceLabel:s.sourceLabel}):s.message&&(e=D_(s.message,s.id,s.isStreaming,s.timestamp,s.sourceLabel));return e?I.createElement(S,{flexDirection:"column"},e):null};function D_(s,e,t,n,r){let o=`msg-${e}`;if(s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="tool_result"))return I.createElement(Ud,{key:o,message:s,timestamp:n});switch(s.role){case "user":return I.createElement(dy,{key:o,message:s,timestamp:n});case "assistant":return I.createElement(my,{key:o,message:s,streaming:t,timestamp:n,sourceLabel:r});case "system":case "tool":let a=s;return a.role==="user"&&Array.isArray(a.content)&&a.content.some(l=>l.type==="tool_result")?I.createElement(Ud,{key:o,message:a,timestamp:n}):I.createElement(S,{key:o},I.createElement(y,{color:"gray",dimColor:true},"[Unknown message type: ",s.role,"]"))}}var qd=I.memo(R_,(s,e)=>s.entry.id===e.entry.id&&s.entry.isStreaming===e.entry.isStreaming);Z();uu();var My=({value:s,placeholder:e="Type a message... (? for help)",disabled:t=false,multiline:n=false,completions:r=[],menuActive:o=false,imageCount:i=0,onChange:a,onSubmit:l,onHistoryUp:c,onHistoryDown:u,onTabComplete:d,onPasteImage:m})=>{let [g,h]=useState(0),[f,v]=useState(false),[b,C]=useState(0),T=s.length-g;useRef(false);useRef("");let N=useRef(s),D=useRef(T);useEffect(()=>{N.current=s,D.current=T;},[s,T]);let $=true,k=useRef(t),M=useRef(o);useEffect(()=>{k.current=t,M.current=o;},[t,o]),et((O,F)=>{if(!(k.current||M.current)){if(O&&(O.includes("[200~")||O.includes("[201~"))){p.debug("INPUT_LINE","Filtered out bracketed paste marker from input");return}if(!F.escape){if(F.tab){if(d){let U=d(s);U&&(a(U),h(0));}return}if((F.meta||F.ctrl)&&(O==="v"||O==="V")&&m&&(p.info("INPUT_LINE","\u{1F3AF} Cmd+V / Ctrl+V detected - checking clipboard for image..."),setTimeout(()=>{cu().then(U=>{U?(m(U),p.info("INPUT_LINE",`\u{1F4CE} Image attached via Cmd+V: ${U.name} (${Math.round(U.data.length/1024)}KB)`)):p.debug("INPUT_LINE","No image in clipboard (Cmd+V fallback)");}).catch(U=>{p.error("INPUT_LINE","Failed to paste image (Cmd+V fallback)",{error:U});});},50)),F.return){if(n&&!F.shift){let U=s.slice(0,T)+`
|
|
1682
1682
|
`+s.slice(T);a(U);return}process.env.CLI_DEBUG==="1"&&p.debug("INPUT_LINE","Enter pressed - submitting",{valueLength:s.length,value:s.substring(0,50),disabled:t}),l(),h(0),v(false);return}if(F.upArrow){c(),h(0);return}if(F.downArrow){u(),h(0);return}if(F.leftArrow){h(Math.min(g+1,s.length));return}if(F.rightArrow){h(Math.max(g-1,0));return}if(F.home||F.ctrl&&O==="a"){h(s.length);return}if(F.end||F.ctrl&&O==="e"){h(0);return}if(F.backspace||F.delete){if(g===s.length)return;let U=T-1,K=s.slice(0,U)+s.slice(U+1);a(K);return}if(!F.ctrl&&!F.meta&&O){let U=s.slice(0,T)+O+s.slice(T);a(U);return}}}},{isActive:$});let _=s.slice(0,T),P=s[T]||" ",j=s.slice(T+1),z=n?s.split(`
|
|
1683
|
-
`):[s];return I.createElement(S,{flexDirection:"column"},I.createElement(S,{flexDirection:n?"column":"row"},!n&&I.createElement(y,{color:"green",bold:true},"> "),t?I.createElement(y,{dimColor:true},s||e):!s?I.createElement(S,null,!n&&I.createElement(y,{inverse:true}," "),I.createElement(y,{dimColor:true},e)):n?z.map((O,F)=>I.createElement(S,{key:F},I.createElement(y,{color:"green",bold:true},F===0?"> ":"\u2502 "),I.createElement(y,null,O))):I.createElement(y,null,_,I.createElement(y,{inverse:true},P),j)),f&&r.length>0&&I.createElement(S,{paddingLeft:2,flexDirection:"column"},I.createElement(y,{color:"yellow"},"Suggestions:"),r.slice(0,5).map((O,F)=>I.createElement(y,{key:F,color:F===b?"cyan":"white",bold:F===b},F===b?"\u2192 ":" ",O))))};var N_=({isRunning:s,statusText:e="",tokenStats:t,streamingTokens:n=0,streamingStartTime:r=null,provider:o,model:i,onContextMenuToggle:a,agentContextStats:l=[],maxDisplayAgents:c=3,runMode:u="single",networkStats:d,cooperateStats:m})=>{let[g,h]=useState(null),[f,v]=useState(0),[b,C]=useState(0),[T,w]=useState(0),[E,N]=useState(0);useEffect(()=>{s?(h(r||Date.now()),v(0)):!s&&(t?.output||0)===0&&(h(null),v(0));},[s,r,t?.output]),useEffect(()=>{if(!s||g===null)return;let V=setInterval(()=>{v(Math.floor((Date.now()-g)/1e3));},500);return ()=>clearInterval(V)},[s,g]),useEffect(()=>{if(!s||n===0){C(0);return}let V=Math.floor(n);if(b===V)return;let ne=V-b,ue=Math.min(Math.abs(ne),20),re=ne/ue,ee=setInterval(()=>{C(ve=>{let L=ve+re;return Math.abs(L-V)<1?V:L});},50);return ()=>clearInterval(ee)},[n,s,b]),useEffect(()=>{let V=t?.output||0;if(T===V)return;let ne=V-T;if(Math.abs(ne)>100){w(V);return}let ue=Math.max(Math.ceil(Math.abs(ne)/10),3),re=ne/ue,ee=setInterval(()=>{w(ve=>{let L=ve+re;return Math.abs(L-V)<1?V:L});},10);return ()=>clearInterval(ee)},[t?.output,T]),useEffect(()=>{if(!s){N(0);return}let ne=(e||"Thinking...").length,ue=setInterval(()=>{N(re=>(re+1)%(ne+3));},80);return ()=>clearInterval(ue)},[s,e]);let D=()=>{if(f<60)return `${f}s`;let V=Math.floor(f/60),ne=f%60;return `${V}m ${ne}s`},$=V=>V>=1e6?(V/1e6).toFixed(1)+"M":V>=1e3?(V/1e3).toFixed(1)+"K":V.toString(),k=t?.contextWindow||0,M=t?.tokensUsedForContext||t?.total||0,_=t?.pressure||0,P=Math.round(_*100),j=()=>_>.8?"red":_>.5?"yellow":"green",z=V=>V.split("").map((ue,re)=>{let ae=re-E;return ae>=0&&ae<2?I.createElement(y,{key:re,color:"white",bold:true},ue):ae>=-1&&ae<0?I.createElement(y,{key:re,color:"cyanBright"},ue):I.createElement(y,{key:re,color:"cyan"},ue)}),O=(()=>{switch(u){case "single":return {icon:"\u{1F464}",label:"Single",color:"cyan"};case "collab":return {icon:"\u{1F91D}",label:"Collab",color:"magenta"};case "cooperate":return {icon:"\u{1F527}",label:"Cooperate",color:"yellow"};case "network":return {icon:"\u{1F310}",label:"Network",color:"blue"};default:return {icon:"\u{1F464}",label:"Single",color:"cyan"}}})(),F=e&&(e.includes("Streaming:")||e.toLowerCase().includes("stream")),U=e?.match(/Streaming:\s*(\w+)/),K=U?U[1]:null,de=l.length>0,W=l.find(V=>V.agentId==="Main"),H=l.filter(V=>V.agentId!=="Main"),oe=H.length>c,J=()=>H.length===0?null:I.createElement(S,null,I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"magenta"},H.length),I.createElement(y,{dimColor:true}," workers"),oe&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2022 Ctrl+G"))),fe=(V,ne)=>{let ue=V.pressure||0,re=Math.round(ue*100),ae=()=>ue>.8?"red":ue>.5?"yellow":"green",ee=()=>{switch(V.status||"idle"){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},{icon:ve,color:L}=ee(),q=V.currentTask?V.currentTask.length>20?V.currentTask.slice(0,17)+"...":V.currentTask:"";return I.createElement(S,{key:V.agentId,justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{dimColor:true},ne?"\u2514\u2500 ":"\u251C\u2500 "),I.createElement(y,{color:L},ve),I.createElement(y,null," "),I.createElement(y,{color:"magenta"},V.agentLabel),q&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{dimColor:true},q))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(V.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(V.output)),I.createElement(y,{dimColor:true}," \u2502 context "),I.createElement(y,{color:"yellow"},$(V.tokensUsedForContext)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},$(V.contextWindow)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:ae()},re,"%"),I.createElement(y,{dimColor:true},")")))};if(u==="network"){let V=d?.teamSize||0,ne=d?.activeAgents||0,ue=d?.currentPhase||"executing",re=d?.currentAgent,ae=d?.totalInputTokens||t?.input||0,ee=d?.totalOutputTokens||t?.output||0,ve=d?.completedTasks,L=d?.totalTasks,Q=(()=>{switch(ue){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})();return I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"blue"},"\u{1F310}"),I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"blue"},V),I.createElement(y,{dimColor:true}," agents"),ne>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"green"},ne),I.createElement(y,{dimColor:true}," active)")),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),re?I.createElement(I.Fragment,null,z(re),I.createElement(y,{dimColor:true},": "),I.createElement(y,{color:Q.color},Q.text)):I.createElement(y,{color:Q.color},Q.text),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(S,null,ee>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,ve!==void 0&&L!==void 0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true},"tasks "),I.createElement(y,{color:"yellow"},ve),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},L),I.createElement(y,{dimColor:true}," \u2502 ")),s&&b>0&&I.createElement(I.Fragment,null,I.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),I.createElement(y,{dimColor:true}," \u2502 ")),I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(ae)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(ee))))}if(u==="cooperate"&&m){let{models:V,phase:ne,totalInputTokens:ue,totalOutputTokens:re,ccbResult:ae,dagProgress:ee}=m,L=(()=>{switch(ne){case "analyzing":return {text:"Analyzing",color:"cyan"};case "ccb_review":return {text:"CCB Review",color:"yellow"};case "dag_planning":return {text:"Planning",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})(),q=()=>V.length===0?null:V.map((le,Ee)=>{let Pe=le.status==="running"?"green":le.status==="completed"?"blue":"gray";return I.createElement(I.Fragment,{key:Ee},Ee>0&&I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:Pe},le.shortName))}),Q=V.filter(le=>le.status==="completed").length;return I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"yellow"},"\u{1F527}"),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),e?z(e):I.createElement(y,{color:L.color},L.text),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")")),b>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ~"),I.createElement(y,{color:"magenta"},Math.floor(b)),I.createElement(y,{dimColor:true}," tok"))):I.createElement(S,null,re>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,V.length>0&&I.createElement(I.Fragment,null,q(),I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:"yellow"},Q),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},V.length),I.createElement(y,{dimColor:true}," \u2502 ")),ae&&I.createElement(I.Fragment,null,I.createElement(y,{color:ae.approved?"green":"red"},ae.approved?"\u2713":"\u2717"),I.createElement(y,{dimColor:true}," CCB "),I.createElement(y,{color:"yellow"},ae.approveCount),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},ae.totalCount),I.createElement(y,{dimColor:true}," \u2502 ")),ee&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true},"DAG "),I.createElement(y,{color:"yellow"},ee.completedNodes),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},ee.totalNodes),I.createElement(y,{dimColor:true}," \u2502 ")),I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(ue||t?.input||0)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(re||t?.output||0))))}if((u==="collab"||u==="cooperate")&&de){let V=W?.pressure||0,ne=Math.round(V*100),ue=()=>V>.8?"red":V>.5?"yellow":"green",re=H.length<=c&&H.length>0,ae=W?.agentLabel||"Main";return I.createElement(S,{flexDirection:"column"},I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:O.color},O.icon),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),I.createElement(y,{bold:true,color:"cyan"},"\u25CF"),I.createElement(y,null," "),F&&K?I.createElement(I.Fragment,null,z(`Streaming: ${K}`)):z(e||"Thinking..."),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(S,null,(W?.output||t?.output||0)>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,W?I.createElement(S,null,I.createElement(y,{dimColor:true},ae,": "),I.createElement(y,{color:"cyan"},$(W.input)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"green"},$(W.output)),(W.cacheCreationTokens||W.cacheReadTokens)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," cache-w "),I.createElement(y,{color:"magenta"},$(W.cacheCreationTokens||0)),I.createElement(y,{dimColor:true}," cache-r "),I.createElement(y,{color:"blue"},$(W.cacheReadTokens||0))),I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"yellow"},$(W.tokensUsedForContext)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},$(W.contextWindow)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:ue()},ne,"%"),I.createElement(y,{dimColor:true},")"),J()):I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(t?.input||0)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(t?.output||0)),J()))),re&&H.map((ee,ve)=>fe(ee,ve===H.length-1)))}return I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:O.color},O.icon),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),I.createElement(y,{bold:true,color:"cyan"},"\u25CF"),I.createElement(y,null," "),F&&K?I.createElement(I.Fragment,null,z(`Streaming: ${K}`)):z(e||"Thinking..."),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true}," \u2022 esc to interrupt"),b>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2022 "),I.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),I.createElement(y,{dimColor:true}," ",F?"chars":"tokens")),I.createElement(y,{dimColor:true},")"))):I.createElement(S,null,(t?.output||0)>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,k>0?I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(t?.input||0)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(t?.output||0)),(t?.cacheCreationTokens||t?.cacheReadTokens)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," cache-w "),I.createElement(y,{color:"magenta"},$(t.cacheCreationTokens||0)),I.createElement(y,{dimColor:true}," cache-r "),I.createElement(y,{color:"blue"},$(t.cacheReadTokens||0))),I.createElement(y,{dimColor:true}," \u2502 context "),I.createElement(y,{color:"yellow"},$(M)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},$(k)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:j()},P,"%"),I.createElement(y,{dimColor:true},")")):I.createElement(y,{dimColor:true},"context: --")))},L_=(s,e)=>!s&&!e?true:!s||!e||s.length!==e.length?false:s.every((t,n)=>{let r=e[n];return t.agentId===r.agentId&&t.input===r.input&&t.output===r.output&&t.pressure===r.pressure&&t.tokensUsedForContext===r.tokensUsedForContext&&t.status===r.status&&t.currentTask===r.currentTask&&t.contextWindow===r.contextWindow&&t.cacheCreationTokens===r.cacheCreationTokens&&t.cacheReadTokens===r.cacheReadTokens}),Py=I.memo(N_,(s,e)=>s.isRunning===e.isRunning&&s.statusText===e.statusText&&s.streamingTokens===e.streamingTokens&&s.streamingStartTime===e.streamingStartTime&&s.tokenStats?.input===e.tokenStats?.input&&s.tokenStats?.output===e.tokenStats?.output&&s.tokenStats?.total===e.tokenStats?.total&&s.tokenStats?.pressure===e.tokenStats?.pressure&&s.tokenStats?.cacheCreationTokens===e.tokenStats?.cacheCreationTokens&&s.tokenStats?.cacheReadTokens===e.tokenStats?.cacheReadTokens&&s.runMode===e.runMode&&s.networkStats?.teamSize===e.networkStats?.teamSize&&s.networkStats?.activeAgents===e.networkStats?.activeAgents&&s.networkStats?.currentPhase===e.networkStats?.currentPhase&&s.networkStats?.currentAgent===e.networkStats?.currentAgent&&s.networkStats?.totalInputTokens===e.networkStats?.totalInputTokens&&s.networkStats?.totalOutputTokens===e.networkStats?.totalOutputTokens&&s.networkStats?.completedTasks===e.networkStats?.completedTasks&&s.networkStats?.totalTasks===e.networkStats?.totalTasks&&s.cooperateStats?.phase===e.cooperateStats?.phase&&s.cooperateStats?.totalInputTokens===e.cooperateStats?.totalInputTokens&&s.cooperateStats?.totalOutputTokens===e.cooperateStats?.totalOutputTokens&&s.cooperateStats?.ccbResult?.approved===e.cooperateStats?.ccbResult?.approved&&s.cooperateStats?.ccbResult?.approveCount===e.cooperateStats?.ccbResult?.approveCount&&s.cooperateStats?.dagProgress?.completedNodes===e.cooperateStats?.dagProgress?.completedNodes&&s.cooperateStats?.models?.length===e.cooperateStats?.models?.length&&L_(s.agentContextStats,e.agentContextStats));var Ry=({isRunning:s,hasInput:e,customHints:t,menuActive:n=false,thinkingEnabled:r=true,accumulatedRunTime:o=0,provider:i,model:a,runMode:l="single"})=>{let[c,u]=useState(o);useEffect(()=>{if(!s){u(o);return}u(o);let f=setInterval(()=>{u(v=>v+1);},1e3);return ()=>clearInterval(f)},[s,o]);let d=()=>{if(c<60)return `${c}s`;let f=Math.floor(c/60),v=c%60;if(f<60)return `${f}m ${v}s`;let b=Math.floor(f/60),C=f%60;return `${b}h ${C}m`},m=()=>{if(!i||!a)return "";let f=i,v=i.indexOf(" (");v>0&&(f=i.substring(0,v));let b=a.length>35?a.substring(0,32)+"...":a;return `${f}/${b}`},h=(()=>{switch(l){case "single":return {label:"SINGLE",color:"cyan"};case "collab":return {label:"COLLAB",color:"magenta"};case "cooperate":return {label:"COOPERATE",color:"yellow"};case "network":return {label:"NETWORK",color:"blue"};default:return {label:"SINGLE",color:"cyan"}}})();return t?I.createElement(S,{justifyContent:"space-between"},I.createElement(y,{color:"yellow"},t)):n?I.createElement(S,{justifyContent:"space-between"},I.createElement(y,{dimColor:true}," ","\u2191\u2193 to select, Enter to confirm, ESC to cancel")):I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{dimColor:true},"? for shortcuts"),c>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2022 "),I.createElement(y,{color:"cyan"},d()),I.createElement(y,{dimColor:true}," session"))),I.createElement(S,null,I.createElement(y,{color:h.color,bold:true},"["),I.createElement(y,{color:h.color},h.label),I.createElement(y,{color:h.color,bold:true},"]"),I.createElement(y,{dimColor:true}," \u2022 "),m()&&I.createElement(I.Fragment,null,I.createElement(y,{color:"magenta",bold:true},"["),I.createElement(y,{color:"magenta"},m()),I.createElement(y,{color:"magenta",bold:true},"]"),I.createElement(y,{dimColor:true}," \u2022 ")),r?I.createElement(y,{color:"cyan"},"Thinking on"):I.createElement(y,{dimColor:true},"Thinking off"),I.createElement(y,{dimColor:true}," (tab to toggle)")))};var Dy=({attachments:s,onRemove:e})=>s.length===0?null:I.createElement(S,{flexDirection:"column",paddingLeft:2,marginBottom:1},I.createElement(y,{color:"magenta",dimColor:true},"Attachments:"),s.map((t,n)=>{let r=t.name||t.path?.split("/").pop()||"unknown",o=t.type?.startsWith("image/")||t.mediaType?.startsWith("image/")||r.match(/\.(png|jpg|jpeg|gif|webp)$/i);return I.createElement(S,{key:n},I.createElement(y,{color:"magenta"},o?"\u{1F4CE} \u{1F5BC}\uFE0F ":"\u{1F4CE} ",r),e&&I.createElement(y,{color:"gray",dimColor:true}," (press \u232B Backspace to remove)"))}));var Ny=({contextWindow:s,tokensUsed:e,systemTokens:t=0,userTokens:n=0,assistantTokens:r=0,toolCallTokens:o=0,toolResultTokens:i=0,compactionThreshold:a=.8,compressionMode:l="sync",agentContextStats:c=[],runMode:u="single",networkStats:d,onClose:m})=>{let g=D=>D>=1e6?`${(D/1e6).toFixed(1)}M`:D>=1e3?`${(D/1e3).toFixed(1)}k`:D.toString(),h=D=>D>.8?"red":D>.5?"yellow":"green",f=({color:D,label:$,tokens:k,total:M,indent:_=2})=>{let P=M>0?(k/M*100).toFixed(2):"0.00";return I.createElement(S,{marginLeft:_},I.createElement(y,{color:D},"\u25A0"),I.createElement(y,null," ",$,": "),I.createElement(y,{color:"yellow"},g(k)),I.createElement(y,{dimColor:true}," tokens (",P,"%)"))},v=({stat:D,indent:$=2})=>{let k=D.cacheCreationTokens||0,M=D.cacheReadTokens||0,_=D.contextWindow||2e5,P=D.tokensUsedForContext||0,j=_>0?P/_:0,z=Math.round(j*100);return I.createElement(S,{marginLeft:$,justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"magenta"},D.agentLabel||D.agentId),D.status&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:D.status==="running"?"green":D.status==="error"?"red":"gray"},D.status==="running"?"\u25CF":D.status==="completed"?"\u2713":D.status==="error"?"\u2717":"\u25CB"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},g(D.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},g(D.output)),(k>0||M>0)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2502 cw "),I.createElement(y,{color:"blue"},g(k)),I.createElement(y,{dimColor:true}," cr "),I.createElement(y,{color:"blue"},g(M))),I.createElement(y,{dimColor:true}," \u2502 ctx "),I.createElement(y,{color:"yellow"},g(P)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},g(_)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:h(j)},z,"%"),I.createElement(y,{dimColor:true},")")))},b=({stat:D,indent:$=2})=>{let k=D.contextWindow>0?D.tokensUsedForContext/D.contextWindow:0,M=Math.round(k*100);return I.createElement(S,{marginLeft:$,justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"magenta"},D.agentLabel||D.agentId),D.status&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:D.status==="running"?"green":D.status==="error"?"red":"gray"},D.status==="running"?"\u25CF":D.status==="completed"?"\u2713":D.status==="error"?"\u2717":"\u25CB"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},g(D.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},g(D.output)),I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"yellow"},g(D.tokensUsedForContext)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},g(D.contextWindow)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:h(k)},M,"%"),I.createElement(y,{dimColor:true},")")))};if(u==="network"){let D=d?.teamSize||c.length||0,$=d?.activeAgents||0,k=d?.totalInputTokens||0,M=d?.totalOutputTokens||0,_=k+M,j=(z=>{switch(z){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Idle",color:"gray"}}})(d?.currentPhase);return I.createElement(S,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1},I.createElement(S,{justifyContent:"space-between",marginBottom:1},I.createElement(S,null,I.createElement(y,{color:"blue"},"\u{1F310}"),I.createElement(y,{bold:true,color:"blue"}," Network Context Overview")),I.createElement(y,{dimColor:true},"(press ESC to close)")),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Team Size: "),I.createElement(y,{color:"blue",bold:true},D),I.createElement(y,{dimColor:true}," agents"),$>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"green"},$),I.createElement(y,{dimColor:true}," active)"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"Current Phase: "),I.createElement(y,{color:j.color,bold:true},j.text),d?.currentAgent&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," - "),I.createElement(y,{color:"cyan"},d.currentAgent))),d?.completedTasks!==void 0&&d?.totalTasks!==void 0&&I.createElement(S,null,I.createElement(y,{dimColor:true},"Tasks: "),I.createElement(y,{color:"yellow"},d.completedTasks),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},d.totalTasks),I.createElement(y,{dimColor:true}," completed"))),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(y,{bold:true,dimColor:true},"Total Token Usage:"),I.createElement(S,{marginLeft:2},I.createElement(y,{dimColor:true},"Input: "),I.createElement(y,{color:"cyan"},g(k)),I.createElement(y,{dimColor:true}," \u2502 Output: "),I.createElement(y,{color:"green"},g(M)),I.createElement(y,{dimColor:true}," \u2502 Total: "),I.createElement(y,{color:"yellow"},g(_)))),c.length>0&&I.createElement(S,{flexDirection:"column"},I.createElement(y,{bold:true,dimColor:true},"Agent Context Details:"),c.map(z=>I.createElement(v,{key:z.agentId,stat:z})),I.createElement(S,{marginTop:1,marginLeft:2},I.createElement(y,{dimColor:true},"Total Tokens: "),I.createElement(y,{color:"yellow"},g(c.reduce((z,A)=>z+A.input+A.output,0))),I.createElement(y,{dimColor:true}," across "),I.createElement(y,{color:"cyan"},c.length),I.createElement(y,{dimColor:true}," agents"))),c.length===0&&I.createElement(S,{marginTop:1},I.createElement(y,{dimColor:true,italic:true},"Agent context details not available yet.")))}if((u==="collab"||u==="cooperate")&&c.length>0){let D=c.find(A=>A.agentId==="Main"),$=c.filter(A=>A.agentId!=="Main"&&A.agentId!=="supervisor"),k=c.reduce((A,O)=>A+O.tokensUsedForContext,0),M=c.reduce((A,O)=>A+O.input,0),_=c.reduce((A,O)=>A+O.output,0),P=u==="collab"?"\u{1F91D}":"\u{1F527}",j=u==="collab"?"Collab":"Cooperate",z=u==="collab"?"magenta":"yellow";return I.createElement(S,{flexDirection:"column",borderStyle:"round",borderColor:z,paddingX:2,paddingY:1},I.createElement(S,{justifyContent:"space-between",marginBottom:1},I.createElement(S,null,I.createElement(y,{color:z},P),I.createElement(y,{bold:true,color:z}," ",j," Context Overview")),I.createElement(y,{dimColor:true},"(press ESC to close)")),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Total Agents: "),I.createElement(y,{color:z,bold:true},c.length),$.length>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," (1 Main + "),I.createElement(y,{color:"cyan"},$.length),I.createElement(y,{dimColor:true}," Workers)"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"Total Tokens: "),I.createElement(y,{color:"cyan"},g(M)),I.createElement(y,{dimColor:true}," in / "),I.createElement(y,{color:"green"},g(_)),I.createElement(y,{dimColor:true}," out"))),D&&I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(y,{bold:true,dimColor:true},"Main Agent:"),I.createElement(b,{stat:D})),$.length>0&&I.createElement(S,{flexDirection:"column"},I.createElement(y,{bold:true,dimColor:true},"Worker Agents (",$.length,"):"),$.map(A=>I.createElement(b,{key:A.agentId,stat:A}))),I.createElement(S,{marginTop:1},I.createElement(y,{dimColor:true},"Combined Context: "),I.createElement(y,{color:"yellow"},g(k)),I.createElement(y,{dimColor:true}," tokens")))}let C=s-e,T=s>0?e/s:0,w=Math.floor(s*a),E=Math.max(0,w-e),N=Math.round(T*100);return I.createElement(S,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},I.createElement(S,{justifyContent:"space-between",marginBottom:1},I.createElement(y,{bold:true,color:"cyan"},"Context Window Details"),I.createElement(y,{dimColor:true},"(press ESC to close)")),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Total: "),I.createElement(y,{color:"yellow"},g(e)),I.createElement(y,{dimColor:true}," / "),I.createElement(y,{color:"yellow"},g(s)),I.createElement(y,{dimColor:true}," tokens ("),I.createElement(y,{color:h(T),bold:true},N,"%"),I.createElement(y,{dimColor:true},")")),I.createElement(S,null,I.createElement(y,{dimColor:true},"Remaining: "),I.createElement(y,{color:"green"},g(C)),I.createElement(y,{dimColor:true}," tokens"))),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Compression: "),I.createElement(y,{color:l==="sync"?"green":"yellow"},l==="sync"?"Sync LLM":"Async LLM"),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"cyan"},Math.round(a*100),"%"),I.createElement(y,{dimColor:true}," threshold)"))),E>0?I.createElement(S,{marginBottom:1},I.createElement(y,{dimColor:true},"Compaction in: "),I.createElement(y,{color:"cyan"},g(E)),I.createElement(y,{dimColor:true}," tokens")):I.createElement(S,{marginBottom:1},I.createElement(y,{color:"red",bold:true},"\u26A0\uFE0F Compaction threshold reached!")),I.createElement(S,{flexDirection:"column"},I.createElement(y,{bold:true,dimColor:true},"Context Breakdown:"),I.createElement(f,{color:"magenta",label:"System",tokens:t,total:e}),I.createElement(f,{color:"cyan",label:"User",tokens:n,total:e}),I.createElement(f,{color:"green",label:"Assistant",tokens:r,total:e}),I.createElement(f,{color:"blue",label:"Tool Calls",tokens:o,total:e}),I.createElement(f,{color:"yellow",label:"Tool Results",tokens:i,total:e}),I.createElement(S,{marginTop:1,marginLeft:2},I.createElement(y,{dimColor:true},"Usage: "),I.createElement(y,{color:h(T)},"\u2588".repeat(Math.floor(T*20))),I.createElement(y,{dimColor:true},"\u2591".repeat(20-Math.floor(T*20))))))};Z();var B_=({inputValue:s,isRunning:e,statusText:t="",tokenStats:n,streamingTokens:r=0,streamingStartTime:o=null,accumulatedRunTime:i=0,provider:a,model:l,customHints:c,attachments:u=[],multiline:d=false,completions:m=[],menuActive:g=false,promptActive:h=false,promptMessage:f,promptHint:v,promptOnCancel:b,thinkingEnabled:C=true,contextMenuActive:T=false,compressionMode:w="sync",compactionThreshold:E=.85,agentContextStats:N=[],runMode:D="single",networkStats:$,cooperateStats:k,onInputChange:M,onSubmit:_,onInterrupt:P,onExit:j,onHistoryUp:z,onHistoryDown:A,onTabComplete:O,onRemoveAttachment:F,onContextMenuToggle:U,onAgentContextScreenToggle:K,onPasteImage:de,onShowInterruptInput:W})=>{let{columns:H}=Co();return et((oe,J)=>{if(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","BottomBar useInput",{key:J,input:oe,menuActive:g,promptActive:h,isRunning:e,inputValue:s.substring(0,20)}),!g){if(e&&oe==="i"&&!J.ctrl&&!J.meta&&W){p.debug("INK_INPUT",'Interrupt input triggered with "i" key'),W();return}if(J.ctrl&&oe==="g"&&K){K();return}if(J.ctrl&&oe==="z"){process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+Z blocked (prevents suspension)");return}if(J.escape){if(p.debug("INK_INPUT","ESC pressed in BottomBar",{isRunning:e,hasInput:!!s,promptActive:h,contextMenuActive:T}),T&&U){U();return}if(h&&b){b(),M("");return}e?P():s&&M("");return}J.ctrl&&oe==="c"&&(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+C pressed",{isRunning:e}),e?P():(p.info("INK_INPUT","\u26A0\uFE0F Ctrl+C pressed - exiting"),j()));}},{isActive:true}),I.createElement(S,{flexDirection:"column"},h&&f&&I.createElement(S,{paddingX:2,paddingY:1},I.createElement(y,{color:"cyan",bold:true},f)),h&&v&&I.createElement(S,{paddingX:2,paddingBottom:1},I.createElement(y,{dimColor:true},v)),!h&&I.createElement(Py,{isRunning:e,statusText:t,tokenStats:n,streamingTokens:r,streamingStartTime:o,provider:a,model:l,onContextMenuToggle:U,agentContextStats:N,runMode:D,networkStats:$,cooperateStats:k}),u.length>0&&I.createElement(Dy,{attachments:u,onRemove:F}),I.createElement(S,{flexDirection:"column"},I.createElement(y,{color:"gray"},"\u2500".repeat(H)),I.createElement(My,{value:s,placeholder:h?v||"Type your answer...":e?"Enter to interrupt and send...":"Type a message...",disabled:g,multiline:d,completions:m,menuActive:g,imageCount:u.length,onChange:M,onSubmit:()=>_(s),onHistoryUp:z,onHistoryDown:A,onTabComplete:O,onPasteImage:de}),I.createElement(y,{color:"gray"},"\u2500".repeat(H))),!h&&I.createElement(Ry,{isRunning:e,hasInput:s.length>0,customHints:c,menuActive:g,thinkingEnabled:C,accumulatedRunTime:i,provider:a,model:l,runMode:D}),T&&n?.contextWindow&&U&&I.createElement(Ny,{contextWindow:n.contextWindow,tokensUsed:n.tokensUsedForContext||n.total,systemTokens:n.systemTokens,userTokens:n.userTokens,assistantTokens:n.assistantTokens,toolCallTokens:n.toolCallTokens,toolResultTokens:n.toolResultTokens,compressionMode:w,compactionThreshold:E,agentContextStats:N,runMode:D,networkStats:$,onClose:U}))},Ly=I.memo(B_);var Yd=({message:s,choices:e,initialIndex:t=0,hint:n,maxVisible:r=20,onSelect:o,onCancel:i,onExit:a})=>{let[l,c]=useState(t),[u,d]=useState(0),[m,g]=useState(null);useEffect(()=>{c(t);},[t]),useEffect(()=>{let b=setTimeout(()=>{g(Date.now());},200);return ()=>clearTimeout(b)},[]),useEffect(()=>{if(e.length<=r){d(0);return}l<u?d(l):l>=u+r&&d(l-r+1);},[l,e.length,r,u]),et((b,C)=>{if(C.ctrl&&b==="c"&&a){process.nextTick(()=>a());return}if(C.escape&&i){process.nextTick(()=>i());return}if(C.upArrow){c(T=>T>0?T-1:e.length-1);return}if(C.downArrow){c(T=>T<e.length-1?T+1:0);return}if(C.return){if(!m)return;process.nextTick(()=>o(e[l].value));return}});let h=Math.min(e.length,r),f=u>0,v=u+h<e.length;return I.createElement(S,{flexDirection:"column"},s&&I.createElement(S,{marginBottom:1,paddingX:2},I.createElement(y,{bold:true,color:"cyan"},s)),n&&I.createElement(S,{marginBottom:1,paddingX:2},I.createElement(y,{dimColor:true},n)),f&&I.createElement(S,{paddingX:2},I.createElement(y,{dimColor:true}," \u2191 more")),e.slice(u,u+h).map((b,C)=>{let T=u+C,w=T===l,E=w?"\u276F ":" ";return I.createElement(S,{key:`${b.value}-${T}`,flexDirection:"row",paddingX:2},I.createElement(y,{color:w?"cyan":void 0,bold:w},E,b.label),b.description&&I.createElement(y,{dimColor:true}," - ",b.description))}),v&&I.createElement(S,{paddingX:2},I.createElement(y,{dimColor:true}," \u2193 more")))};var $y=({onSubmit:s,onCancel:e})=>{let[t,n]=useState(""),[r,o]=useState(0),i=t.length-r;et((u,d)=>{if(d.escape){e();return}if(d.return){let m=t.trim();m&&s(m);return}if(d.backspace||d.delete){if(r===t.length)return;let m=i-1,g=t.slice(0,m)+t.slice(m+1);n(g);return}if(d.leftArrow){o(Math.min(r+1,t.length));return}if(d.rightArrow){o(Math.max(r-1,0));return}if(d.home||d.ctrl&&u==="a"){o(t.length);return}if(d.end||d.ctrl&&u==="e"){o(0);return}if(!d.ctrl&&!d.meta&&u){let m=t.slice(0,i)+u+t.slice(i);n(m);return}},{isActive:true});let a=t.slice(0,i),l=t[i]||" ",c=t.slice(i+1);return I.createElement(S,{flexDirection:"column",borderStyle:"double",borderColor:"yellow",paddingX:2,paddingY:1,width:"80%"},I.createElement(S,{marginBottom:1,justifyContent:"center"},I.createElement(y,{bold:true,color:"yellow"},"\u2728 \u63D2\u961F\u6D88\u606F - \u5C06\u5728\u4E0B\u6B21\u8BF7\u6C42\u65F6\u53D1\u9001")),I.createElement(S,{flexDirection:"column"},I.createElement(y,{dimColor:true},"\u8F93\u5165\u4F60\u7684\u6D88\u606F:"),I.createElement(S,{marginTop:1},I.createElement(y,{color:"green",bold:true},"\u276F "),t?I.createElement(y,null,a,I.createElement(y,{inverse:true},l),c):I.createElement(S,null,I.createElement(y,{inverse:true}," "),I.createElement(y,{dimColor:true},"\u8F93\u5165\u6D88\u606F...")))),I.createElement(S,{marginTop:1,justifyContent:"space-between"},I.createElement(y,{dimColor:true},"Enter: \u786E\u8BA4"),I.createElement(y,{dimColor:true},"ESC: \u53D6\u6D88")))};var Bs=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:String(s),F_=s=>{switch(s){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},By=({agentContextStats:s,onClose:e})=>{let{columns:t}=Co();et((r,o)=>{(o.escape||r==="q")&&e();},{isActive:true});let n=[...s].sort((r,o)=>r.agentId==="Main"?-1:o.agentId==="Main"?1:r.agentLabel.localeCompare(o.agentLabel));return I.createElement(S,{flexDirection:"column",width:"100%"},I.createElement(S,{justifyContent:"space-between"},I.createElement(y,{bold:true,color:"cyan"},"Agent Context Overview"),I.createElement(y,{dimColor:true},"ESC to close")),I.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),n.length===0?I.createElement(y,{dimColor:true},"No agent context stats available."):n.map(r=>{let o=r.contextWindow||0,i=r.tokensUsedForContext||0,a=o>0?i/o:0,l=Math.round(a*100),{icon:c,color:u}=F_(r.status),d=r.currentTask?r.currentTask.length>40?`${r.currentTask.slice(0,37)}...`:r.currentTask:"";return I.createElement(S,{key:r.agentId,justifyContent:"space-between",marginTop:1},I.createElement(S,null,I.createElement(y,{color:"magenta"},r.agentLabel),I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:u},c),d&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{dimColor:true},d))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},Bs(r.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},Bs(r.output)),(r.cacheCreationTokens||r.cacheReadTokens)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," cache-w "),I.createElement(y,{color:"magenta"},Bs(r.cacheCreationTokens||0)),I.createElement(y,{dimColor:true}," cache-r "),I.createElement(y,{color:"blue"},Bs(r.cacheReadTokens||0))),I.createElement(y,{dimColor:true}," \u2502 context "),I.createElement(y,{color:"yellow"},Bs(i)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},Bs(o)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:a>.8?"red":a>.5?"yellow":"green"},l,"%"),I.createElement(y,{dimColor:true},")")))}),I.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),I.createElement(y,{dimColor:true},"Tip: Press Q or ESC to return"))};Zd();Z();var K_=[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg"];function J_(s){if(!s)return false;let e=s.trim(),t=e.toLowerCase(),n=K_.some(o=>t.endsWith(o)),r=e.startsWith("/")||e.startsWith("./")||e.startsWith("~/")||e.includes("/")&&n;return n&&r}var Fy=({staticEntries:s=[],pendingEntries:e=[],isRunning:t,statusText:n="",tokenStats:r,streamingTokens:o=0,streamingStartTime:i=null,accumulatedRunTime:a=0,version:l=Cl,provider:c="OpenAI",model:u="gpt-4",workDir:d=process.cwd(),showHeader:m=true,thinkingEnabled:g=true,selectMenuOptions:h=null,textPromptOptions:f=null,contextMenuActive:v=false,agentContextScreenActive:b=false,compressionMode:C="sync",compactionThreshold:T=.85,agentContextStats:w=[],runMode:E="single",networkStats:N,cooperateStats:D,commandOutput:$=[],attachedImages:k=[],interruptInputActive:M=false,getCompletions:_,onStaticRendered:P,onSubmit:j,onInterrupt:z,onExit:A,onContextMenuToggle:O,onAgentContextScreenToggle:F,onClearCommandOutput:U,onAttachImage:K,onClearImages:de,onInterruptInputSubmit:W,onInterruptInputCancel:H,onShowInterruptInput:oe})=>{let[J,fe]=useState(""),[V,ne]=useState([]),[ue,re]=useState(-1),[ae,ee]=useState(null),ve=useRef(false),L=useContext(Zr);useEffect(()=>{if(!L?.internal_eventEmitter||!K)return;let Y=me=>{se("CLI_APP",`\u{1F4CE} Received image-paste event from vendor Ink: ${me.name}`),K(me);};return L.internal_eventEmitter.on("image-paste",Y),()=>{L.internal_eventEmitter.off("image-paste",Y);}},[L,K]),useEffect(()=>{f?.defaultValue&&fe(f.defaultValue);},[f?.defaultValue]),et((Y,me)=>{if(me.escape){if(b)return;ae?ee(null):$.length>0&&U&&U();}},{isActive:true});let q=e.filter(Y=>Y.type!=="thinking"&&Y.type!=="reasoning"),Q=Y=>{if(!Y)return false;let{content:me}=Y;return typeof me=="string"?me.trim().length>0:Array.isArray(me)?me.some(pe=>{if(!pe||typeof pe!="object"||!("type"in pe))return false;switch(pe.type){case "text":return typeof pe.text=="string"&&pe.text.trim().length>0;case "image_url":return true;case "tool_use":return true;case "tool_result":return pe.content!==null&&pe.content!==void 0&&String(pe.content).trim().length>0;case "thinking":return typeof pe.thinking=="string"&&pe.thinking.trim().length>0;case "redacted_thinking":return typeof pe.data=="string"&&pe.data.trim().length>0;default:return true}}):false},le=Y=>{if(Y.message)return Q(Y.message);let me=typeof Y.text=="string"&&Y.text.trim().length>0,pe=Y.type==="plan"&&!!Y.planSteps&&Y.planSteps.length>0,_e=(Y.type==="pipeline_node_start"||Y.type==="pipeline_node_complete"||Y.type==="pipeline_node_fail"||Y.type==="pipeline_node_retry")&&(Y.pipelineNode||Y.pipelineNodeRetry),Ot=(Y.type==="network_node_start"||Y.type==="network_node_complete"||Y.type==="network_node_fail")&&Y.networkNode,He=(Y.type==="ccb_review"||Y.type==="ccb_agent_review"||Y.type==="ccb_retry"||Y.type==="ccb_failed")&&!!(Y.ccbReview||Y.ccbAgentReview||Y.ccbRetry||Y.ccbFailed),Wt=Y.type==="pipeline_dag"&&!!Y.pipelineDAG;return !!(me||pe||_e||Ot||He||Wt)},Ee=useMemo(()=>q.filter(le),[q]),Pe=useMemo(()=>s.filter(le),[s]),G=m&&!ve.current,X=I.useCallback((Y,me)=>Y,[]),te=useMemo(()=>{let Y=[],me=Pe.length+Ee.length;return G&&Y.push(I.createElement(uy,{key:"header",version:l,provider:c,model:u,workDir:d})),Pe.forEach((pe,_e)=>{Y.push(I.createElement(qd,{key:`static-entry-${pe.id}`,entry:pe})),(_e<Pe.length-1||me>Pe.length)&&Y.push(I.createElement(y,{key:`static-spacer-${pe.id}`},""));}),Y},[G,Pe,Ee.length,l,c,u,d]);if(useEffect(()=>{!G&&s.length===0||(G&&(ve.current=true),P?.());},[G,s.length,P]),b)return I.createElement(By,{agentContextStats:w,onClose:()=>F?.()});let Ne=Y=>{if(f){if(!Y.trim()&&!f.allowEmpty)return;f.onSubmit(Y),fe("");return}let me=k.length>0,pe=Y.trim().length>0;(pe||me)&&(pe&&ne([...V,Y]),re(-1),fe(""),j(Y,me?k:void 0));},Re=()=>{if(V.length===0)return;let Y=ue+1;Y<V.length&&(re(Y),fe(V[V.length-1-Y]));},De=()=>{if(ue<=0){re(-1),fe("");return}let Y=ue-1;re(Y),fe(V[V.length-1-Y]);},ke=Y=>{if(!_)return null;let me=_(Y);if(me.length===0)return null;if(me.length===1)return me[0];let pe=me.map(_e=>({label:_e,value:_e,description:void 0}));return ee({message:"Select completion:",choices:pe,initialIndex:0,onSelect:_e=>{fe(_e),ee(null);},onCancel:()=>{ee(null);}}),null};return I.createElement(S,{flexDirection:"column",width:"100%"},I.createElement(ua,{items:te},X),Ee.map((Y,me)=>I.createElement(S,{key:`pending-wrapper-${Y.id}`,flexDirection:"column"},I.createElement(qd,{entry:Y}),me<Ee.length-1&&I.createElement(y,null,""))),I.createElement(y,null,`
|
|
1684
|
-
`),I.createElement(S,{flexShrink:0,flexDirection:"column"},I.createElement(Ly,{inputValue:J,isRunning:t,statusText:n,tokenStats:r,streamingTokens:o,streamingStartTime:i,accumulatedRunTime:a,provider:c,model:u,menuActive:!!h||!!ae,promptActive:!!f,promptMessage:f?.message,promptHint:f?.hint,promptOnCancel:f?.onCancel,thinkingEnabled:g,contextMenuActive:v,compressionMode:C,compactionThreshold:T,agentContextStats:w,runMode:E,networkStats:N,cooperateStats:D,attachments:k,onInputChange:Y=>{if(K&&J_(Y)){K(Y.trim());return}fe(Y);},onSubmit:Ne,onInterrupt:z,onExit:A,onHistoryUp:Re,onHistoryDown:De,onTabComplete:ke,onContextMenuToggle:O,onAgentContextScreenToggle:F,onRemoveAttachment:de?Y=>{de();}:void 0,onPasteImage:K,onShowInterruptInput:oe}),h&&I.createElement(Yd,{message:h.message,choices:h.choices,initialIndex:h.initialIndex,hint:h.hint,onSelect:h.onSelect,onCancel:h.onCancel,onExit:A}),ae&&I.createElement(Yd,{message:ae.message,choices:ae.choices,initialIndex:ae.initialIndex,hint:ae.hint,onSelect:ae.onSelect,onCancel:ae.onCancel,onExit:A}),$.length>0&&I.createElement(S,{flexDirection:"column",paddingX:2,paddingY:1,borderStyle:"round",borderColor:"gray"},$.map((Y,me)=>I.createElement(y,{key:me},Y)))),M&&W&&H&&I.createElement(S,{flexDirection:"column",justifyContent:"center",alignItems:"center",marginTop:5},I.createElement($y,{onSubmit:W,onCancel:H})))};Z();var Tl=class s{appInstance=null;messages=[];staticEntries=[];nextEntryId=1;isRunning=false;statusText="";tokenStats={input:0,output:0,total:0,contextWindow:void 0,tokensUsedForContext:0,pressure:0};version="";provider="";model="";workDir="";showHeader=true;thinkingEnabled=true;callbacks;forceUpdate=null;selectMenuOptions=null;textPromptOptions=null;contextMenuActive=false;agentContextScreenActive=false;commandOutput=[];getCompletions;memoryLogTimer=null;attachedImages=[];pendingEntries=[];queuedMessages=[];nextQueuedMessageId=1;interruptInputActive=false;runMode="single";streamingTokens=0;streamingStartTime=null;accumulatedRunTime=0;runningStartTime=null;compressionMode="sync";compactionThreshold=.85;agentContextStats=new Map;networkStats=null;cooperateStats=null;static MAX_QUEUED_STATIC=50;constructor(e){this.callbacks=e;}setCompletionFunction(e){this.getCompletions=e;}start(){p.info("INK","Starting Ink runtime"),this.startMemorySampler();let e=()=>{let[,t]=useState(0);return useEffect(()=>(this.forceUpdate=()=>{let n=Date.now();p.debug("RUNTIME",`>>> forceUpdate called, staticEntries=${this.staticEntries.length}, pendingEntries=${this.pendingEntries.length}`),t(o=>o+1);let r=Date.now()-n;r>50&&p.warn("RUNTIME",`\u26A0\uFE0F forceUpdate slow: setCounter took ${r}ms`);},()=>{this.forceUpdate=null;}),[]),I.createElement(Fy,{staticEntries:this.staticEntries,pendingEntries:this.pendingEntries,isRunning:this.isRunning,statusText:this.statusText,tokenStats:this.tokenStats,streamingTokens:this.streamingTokens,streamingStartTime:this.streamingStartTime,accumulatedRunTime:this.accumulatedRunTime,compressionMode:this.compressionMode,compactionThreshold:this.compactionThreshold,agentContextStats:this.getAgentContextStats(),runMode:this.runMode,networkStats:this.networkStats||void 0,cooperateStats:this.cooperateStats||void 0,version:this.version,provider:this.provider,model:this.model,workDir:this.workDir,showHeader:this.showHeader,thinkingEnabled:this.thinkingEnabled,selectMenuOptions:this.selectMenuOptions,textPromptOptions:this.textPromptOptions,contextMenuActive:this.contextMenuActive,agentContextScreenActive:this.agentContextScreenActive,commandOutput:this.commandOutput,attachedImages:this.attachedImages,interruptInputActive:this.interruptInputActive,getCompletions:this.getCompletions,onStaticRendered:void 0,onSubmit:(n,r)=>{let o=r||this.attachedImages;this.attachedImages=[],this.callbacks.onSubmit(n,o);},onInterrupt:this.callbacks.onInterrupt,onExit:this.callbacks.onExit,onContextMenuToggle:()=>{this.contextMenuActive=!this.contextMenuActive,this.forceUpdate?.();},onAgentContextScreenToggle:()=>{this.agentContextScreenActive=!this.agentContextScreenActive,this.forceUpdate?.();},onClearCommandOutput:()=>{this.clearCommandOutput();},onAttachImage:n=>{this.attachImage(n);},onClearImages:()=>{this.clearAttachedImages();},onInterruptInputSubmit:n=>{this.handleInterruptInputSubmit(n);},onInterruptInputCancel:()=>{this.hideInterruptInput();},onShowInterruptInput:()=>{this.showInterruptInput();}})};this.appInstance=rs(I.createElement(e,null),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:false,patchConsole:false});try{process.stdout.isTTY&&!process.stdout.destroyed&&(process.stdout.write("\x1B[?2004h"),p.info("INK","Bracketed paste mode enabled for image paste detection"));}catch(t){p.warn("INK","Failed to enable bracketed paste mode",{error:t});}try{p.debug("TTY_STATE","\u{1F6E1}\uFE0F [INK] Re-registering SIGTSTP ignore handler after Ink starts"),process.removeAllListeners("SIGTSTP"),process.on("SIGTSTP","ignore"),p.debug("TTY_STATE","\u2705 [INK] SIGTSTP handler re-registered (Ctrl+Z ignored)"),process.env.CLI_DEBUG==="1"&&p.debug("INK","SIGTSTP handler registered (Ctrl+Z ignored)");}catch{p.debug("TTY_STATE","\u26A0\uFE0F [INK] SIGTSTP not supported on this platform"),process.env.CLI_DEBUG==="1"&&p.debug("INK","SIGTSTP not supported on this platform");}p.info("INK","Ink runtime started");}stop(){try{process.stdout.isTTY&&!process.stdout.destroyed&&(process.stdout.write("\x1B[?2004l"),p.debug("INK","Bracketed paste mode disabled"));}catch(e){p.debug("INK","Failed to disable bracketed paste mode (ignored)",{error:e});}this.appInstance&&(this.appInstance.unmount(),this.appInstance=null,p.info("INK","Ink runtime stopped")),this.stopMemorySampler();}addMessage(e){this.messages=[...this.messages.slice(-4),e],this.forceUpdate?.();}addEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};return this.staticEntries.length>=s.MAX_QUEUED_STATIC&&(p.warn("INK_RUNTIME",`Static queue reached limit (${this.staticEntries.length}). Forcing immediate render to prevent OOM.`),this.forceUpdate?.(),setImmediate(()=>{this.clearStaticEntries();})),this.staticEntries=[...this.staticEntries,t],p.debug("INK_RUNTIME",`Queued static entry ${t.id}. Pending static: ${this.staticEntries.length}`),this.forceUpdate?.(),t.id}updateEntry(e,t){let n=this.staticEntries.findIndex(o=>o.id===e);if(n>=0){this.staticEntries=this.staticEntries.map((o,i)=>i===n?{...o,...t}:o),this.forceUpdate?.();return}let r=this.pendingEntries.findIndex(o=>o.id===e);r>=0&&(this.pendingEntries=this.pendingEntries.map((o,i)=>i===r?{...o,...t}:o),this.forceUpdate?.());}getEntry(e){return this.staticEntries.find(t=>t.id===e)||this.pendingEntries.find(t=>t.id===e)}addPendingEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};if(this.pendingEntries.length>=10){p.warn("INK_RUNTIME",`Too many pending entries (${this.pendingEntries.length}). Auto-committing oldest.`);let r=this.pendingEntries[0];this.staticEntries=[...this.staticEntries,r],this.pendingEntries=this.pendingEntries.slice(1);}return this.pendingEntries=[...this.pendingEntries,t],p.debug("INK_RUNTIME",`Added pending entry ${t.id}. Pending: ${this.pendingEntries.length}`),this.forceUpdate?.(),t.id}updatePendingEntry(e,t){let n=this.pendingEntries.findIndex(r=>r.id===e);n>=0&&(this.pendingEntries=this.pendingEntries.map((r,o)=>o===n?{...r,...t}:r),this.forceUpdate?.());}updatePendingEntryByKey(e,t){let n=this.pendingEntries.findIndex(r=>r.entryKey===e);if(n>=0)this.pendingEntries=this.pendingEntries.map((r,o)=>o===n?{...r,...t,entryKey:e,timestamp:new Date}:r);else {let r={...t,entryKey:e,id:this.nextEntryId++,timestamp:new Date};this.pendingEntries=[...this.pendingEntries,r];}this.forceUpdate?.();}commitPendingEntryByKey(e){let t=this.pendingEntries.findIndex(n=>n.entryKey===e);if(t>=0){let n=this.pendingEntries[t];return this.pendingEntries=this.pendingEntries.filter((r,o)=>o!==t),this.staticEntries=[...this.staticEntries,{...n,isStreaming:false,isComplete:true}],p.debug("INK_RUNTIME",`Committed entry by key ${e}. Static: ${this.staticEntries.length}, Pending: ${this.pendingEntries.length}`),this.forceUpdate?.(),true}return false}commitPendingEntry(e){let t=this.pendingEntries.findIndex(n=>n.id===e);if(t>=0){let n=this.pendingEntries[t];this.pendingEntries=this.pendingEntries.filter((r,o)=>o!==t),this.staticEntries=[...this.staticEntries,n],p.debug("INK_RUNTIME",`Committed entry ${e}. Static: ${this.staticEntries.length}, Pending: ${this.pendingEntries.length}`),this.forceUpdate?.();}else p.warn("INK_RUNTIME",`Cannot commit entry ${e} - not found in pending entries`);}clearPendingEntries(){this.pendingEntries.length>0&&(this.pendingEntries=[],this.forceUpdate?.());}updateStreamingStats(e){this.streamingTokens=e,this.streamingStartTime||(this.streamingStartTime=Date.now()),this.forceUpdate?.();}resetStreamingStats(){this.streamingTokens=0,this.streamingStartTime=null;}getAccumulatedRunTime(){if(this.isRunning&&this.runningStartTime!==null){let e=Math.floor((Date.now()-this.runningStartTime)/1e3);return this.accumulatedRunTime+e}return this.accumulatedRunTime}resetAccumulatedRunTime(){this.accumulatedRunTime=0,this.runningStartTime=null,this.forceUpdate?.();}setCompressionMode(e){this.compressionMode!==e&&(this.compressionMode=e,this.forceUpdate?.());}setCompactionThreshold(e){this.compactionThreshold!==e&&(this.compactionThreshold=e,this.forceUpdate?.());}updateAgentContext(e,t){this.agentContextStats.set(e,t),this.forceUpdate?.();}clearAgentContext(e){this.agentContextStats.has(e)&&(this.agentContextStats.delete(e),this.forceUpdate?.());}clearAllAgentContexts(){this.agentContextStats.size>0&&(this.agentContextStats.clear(),this.forceUpdate?.());}getAgentContextStats(){return Array.from(this.agentContextStats.values()).sort((t,n)=>t.agentId==="supervisor"?-1:n.agentId==="supervisor"?1:t.agentId.localeCompare(n.agentId))}updateLastMessage(e){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1];if(typeof t.content=="string")t.content=e;else if(Array.isArray(t.content)){let n=t.content.find(r=>r.type==="text");n&&"text"in n&&(n.text=e);}this.forceUpdate?.();}getLastMessageText(){if(this.messages.length===0)return "";let e=this.messages[this.messages.length-1];if(typeof e.content=="string")return e.content;if(Array.isArray(e.content)){let t=e.content.find(n=>n.type==="text");if(t&&"text"in t)return t.text||""}return ""}setRunning(e){if(this.isRunning!==e){if(e)this.runningStartTime=Date.now();else if(this.runningStartTime!==null){let t=Math.floor((Date.now()-this.runningStartTime)/1e3);this.accumulatedRunTime+=t,this.runningStartTime=null;}this.isRunning=e,this.forceUpdate?.();}}setStatusText(e){this.statusText!==e&&(this.statusText=e,this.forceUpdate?.());}setTokenStats(e){p.info("DEBUG_CTX",`InkRuntime.setTokenStats: received contextWindow=${e.contextWindow}, current=${this.tokenStats.contextWindow}`);let t=e.contextWindow!==void 0?e.contextWindow:this.tokenStats.contextWindow;(this.tokenStats.input!==e.input||this.tokenStats.output!==e.output||this.tokenStats.total!==e.total||this.tokenStats.contextWindow!==t||this.tokenStats.tokensUsedForContext!==e.tokensUsedForContext||this.tokenStats.pressure!==e.pressure||this.tokenStats.toolTokens!==e.toolTokens||this.tokenStats.messageTokens!==e.messageTokens||this.tokenStats.systemTokens!==e.systemTokens||this.tokenStats.userTokens!==e.userTokens||this.tokenStats.assistantTokens!==e.assistantTokens||this.tokenStats.toolCallTokens!==e.toolCallTokens||this.tokenStats.toolResultTokens!==e.toolResultTokens||this.tokenStats.cacheCreationTokens!==e.cacheCreationTokens||this.tokenStats.cacheReadTokens!==e.cacheReadTokens)&&(this.tokenStats={...e,contextWindow:t,tokensUsedForContext:e.tokensUsedForContext??this.tokenStats.tokensUsedForContext,pressure:e.pressure??this.tokenStats.pressure},p.info("DEBUG_CTX",`InkRuntime.setTokenStats: after update contextWindow=${this.tokenStats.contextWindow}`),this.forceUpdate?.());}clearMessages(){p.warn("INK_RUNTIME",`clearMessages called! This will clear pending/static queues. Messages: ${this.messages.length}`),this.messages=[],this.staticEntries=[],this.pendingEntries=[],this.forceUpdate?.();}setCommandOutput(e){p.debug("INK_RUNTIME","Set command output",{lineCount:e.length}),this.commandOutput=e,this.forceUpdate?.();}clearCommandOutput(){p.debug("INK_RUNTIME","Clear command output"),this.commandOutput=[],this.forceUpdate?.();}attachImage(e){let t;if(typeof e=="string")if(e.startsWith("data:")){let r=e.match(/^data:([^;]+);base64,(.+)$/);if(r){let o=`image_${Date.now()}.png`;t={mediaType:r[1],data:r[2],name:o};}else {p.error("INK_RUNTIME","Invalid data URL format",{imageData:e});return}}else {let r=e.split("/").pop()||e;t={path:e,name:r};}else t=e;if(this.attachedImages.some(r=>r.path&&t.path&&r.path===t.path||r.data&&t.data&&r.data===t.data)){p.debug("INK_RUNTIME","Image already attached");return}this.attachedImages.push(t),p.info("INK_RUNTIME",`\u{1F4CE} Attached image #${this.attachedImages.length}: ${t.name||"unnamed"}`),this.forceUpdate?.();}clearAttachedImages(){this.attachedImages.length>0&&(p.debug("INK_RUNTIME",`Cleared ${this.attachedImages.length} attached images`),this.attachedImages=[],this.forceUpdate?.());}getAttachedImages(){return [...this.attachedImages]}showInterruptInput(){p.debug("INK_RUNTIME","Show interrupt input"),this.interruptInputActive=true,this.forceUpdate?.();}hideInterruptInput(){p.debug("INK_RUNTIME","Hide interrupt input"),this.interruptInputActive=false,this.forceUpdate?.();}handleInterruptInputSubmit(e){let t={id:this.nextQueuedMessageId++,text:e,timestamp:new Date};this.queuedMessages.push(t),p.info("INK_RUNTIME",`\u{1F4E8} Queued interrupt message #${t.id}: "${e.substring(0,50)}..."`),this.addEntry({type:"queued_message",text:"\u2728 \u63D2\u961F\u6D88\u606F (\u5C06\u5728\u4E0B\u6B21\u8BF7\u6C42\u65F6\u53D1\u9001)",details:e}),this.hideInterruptInput();}getAndClearQueuedMessages(){let e=[...this.queuedMessages];return this.queuedMessages=[],e.length>0&&p.info("INK_RUNTIME",`\u{1F4E4} Returning ${e.length} queued messages to main loop`),e}hasQueuedMessages(){return this.queuedMessages.length>0}addAgentSpawnEntry(e,t,n,r){return this.addEntry({type:"agent_spawn",agentId:e,agentIndex:t,agentStatus:"running",agentTask:n,agentModel:r,text:n})}addAgentProgressEntry(e,t,n,r){return this.addEntry({type:"agent_progress",agentId:e,agentIndex:t,agentStatus:"running",agentProgress:n,text:r})}addAgentCompleteEntry(e,t,n){return this.addEntry({type:"agent_complete",agentId:e,agentIndex:t,agentStatus:"completed",text:n})}addAgentErrorEntry(e,t,n){return this.addEntry({type:"agent_error",agentId:e,agentIndex:t,agentStatus:"error",agentError:n,text:n})}setVersion(e){this.version=e,this.forceUpdate?.();}setProvider(e){this.provider=e,this.forceUpdate?.();}setModel(e){this.model=e,this.forceUpdate?.();}setRunMode(e){this.runMode=e,e!=="network"&&(this.networkStats=null),this.forceUpdate?.();}updateNetworkStats(e){this.networkStats||(this.networkStats={teamSize:0,activeAgents:0,totalInputTokens:0,totalOutputTokens:0}),Object.assign(this.networkStats,e),this.forceUpdate?.();}clearNetworkStats(){this.networkStats=null,this.forceUpdate?.();}getNetworkStats(){return this.networkStats}updateCooperateStats(e){this.cooperateStats||(this.cooperateStats={models:[],totalInputTokens:0,totalOutputTokens:0}),Object.assign(this.cooperateStats,e),this.forceUpdate?.();}clearCooperateStats(){this.cooperateStats=null,this.forceUpdate?.();}getCooperateStats(){return this.cooperateStats}setWorkDir(e){this.workDir=e,this.forceUpdate?.();}setShowHeader(e){this.showHeader=e,this.forceUpdate?.();}setThinkingEnabled(e){this.thinkingEnabled!==e&&(this.thinkingEnabled=e,this.forceUpdate?.());}showSelectMenu(e){if(p.debug("INK_RUNTIME","Show select menu",{options:e}),process.stdin.isTTY&&!process.stdin.destroyed){let t=process.stdin.isPaused?.()||false;process.stdin.isRaw||false;if(t){process.env.CLI_DEBUG==="1"&&p.debug("INK_RUNTIME",`showSelectMenu: Resuming stdin (wasPaused=${t})`);try{process.stdin.resume(),p.info("INK_RUNTIME","\u2713 Stdin resumed for SelectMenu");}catch(r){p.error("INK_RUNTIME","Failed to resume stdin for SelectMenu",{error:r});}}}this.selectMenuOptions=e,this.forceUpdate?.();}hideSelectMenu(){p.debug("INK_RUNTIME","Hide select menu"),this.selectMenuOptions=null,this.forceUpdate?.(),process.nextTick(()=>{this.forceUpdate?.();});}isSelectMenuActive(){return this.selectMenuOptions!==null}updateSelectMenuIndex(e){if(!this.selectMenuOptions)return;let t=Math.max(0,this.selectMenuOptions.choices.length-1),n=Math.max(0,Math.min(e,t));this.selectMenuOptions={...this.selectMenuOptions,initialIndex:n},this.forceUpdate?.();}showTextPrompt(e){if(p.debug("INK_RUNTIME","Show text prompt",{options:e}),process.stdin.isTTY&&!process.stdin.destroyed){let t=process.stdin.isPaused?.()||false;if(t){process.env.CLI_DEBUG==="1"&&p.debug("INK_RUNTIME",`showTextPrompt: Resuming stdin (wasPaused=${t})`);try{process.stdin.resume(),p.info("INK_RUNTIME","\u2713 Stdin resumed for TextPrompt");}catch(n){p.error("INK_RUNTIME","Failed to resume stdin for TextPrompt",{error:n});}}}this.textPromptOptions=e,this.forceUpdate?.();}hideTextPrompt(){p.debug("INK_RUNTIME","Hide text prompt"),this.textPromptOptions=null,this.forceUpdate?.();}showContextMenu(){p.debug("INK_RUNTIME","Show context menu"),this.contextMenuActive=true,this.forceUpdate?.();}hideContextMenu(){p.debug("INK_RUNTIME","Hide context menu"),this.contextMenuActive=false,this.forceUpdate?.();}getContextMenuActive(){return this.contextMenuActive}clearStaticEntries(){if(this.staticEntries.length===0)return;let e=this.staticEntries.length;p.debug("INK_RUNTIME",`Clearing ${e} static entries from memory`),this.staticEntries=[],global.gc&&e>10&&(p.debug("INK_RUNTIME","Triggering manual GC after clearing entries"),setImmediate(()=>{global.gc&&global.gc();}));}startMemorySampler(){this.memoryLogTimer||process.env.INK_MEM!=="1"||(this.memoryLogTimer=setInterval(()=>{let e=process.memoryUsage(),t=n=>Math.round(n/1024/1024*10)/10;p.info("INK_MEM","usage",{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),heapTotalMB:t(e.heapTotal),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers??0),pendingEntries:this.pendingEntries.length,queuedStatic:this.staticEntries.length,isRunning:this.isRunning});},1e4));}stopMemorySampler(){this.memoryLogTimer&&(clearInterval(this.memoryLogTimer),this.memoryLogTimer=null);}};Z();var wl=class{runtime;config;callbacks;currentThinkingText="";lastMessageRole=null;lastEntryId=null;tokenStats={inputTokens:0,outputTokens:0,totalTokens:0};memory;streamingTextPendingId=null;streamingReasoningPendingId=null;streamingTextBuffer="";streamingReasoningBuffer="";streamingReasoningType="thinking";streamingToolChars=0;toolLogIdByToolId=new Map;toolLogDetailsByToolId=new Map;toolLogNameByToolId=new Map;toolLogOutputByToolId=new Map;toolLogSourceLabelByToolId=new Map;streamingSourceLabel=null;streamingSourceType=null;agentBuffers=new Map;activeAgentId=null;constructor(e){this.config=e,this.memory=e.memory,this.runtime=new Tl({onSubmit:(t,n)=>{this.callbacks?.onSubmit&&this.callbacks.onSubmit(t,n);},onInterrupt:()=>{this.callbacks?.onInterrupt&&this.callbacks.onInterrupt();},onExit:()=>{this.callbacks?.onExit&&this.callbacks.onExit();}});}start(e){this.callbacks=e,this.runtime.setVersion(this.config.version),this.runtime.setProvider(this.config.provider),this.runtime.setModel(this.config.model),this.runtime.setWorkDir(this.config.workDir),this.config.getCompletions&&this.runtime.setCompletionFunction(this.config.getCompletions),this.runtime.start(),p.info("INK_ADAPTER","Ink UI started");}stop(){this.runtime.stop(),this.callbacks=void 0,p.info("INK_ADAPTER","Ink UI stopped");}addUserMessage(e,t){let n=[{type:"text",text:e}];if(t&&t.length>0)for(let o of t)n.push({type:"image_url",image_url:{url:`file://${o.path}`}});let r={role:"user",content:n};this.lastEntryId=this.runtime.addEntry({type:"user",message:r}),this.lastMessageRole="user";}addAssistantMessage(e=""){if(e===""){this.lastMessageRole="assistant";return}let t={role:"assistant",content:[{type:"text",text:e}]};this.lastEntryId=this.runtime.addEntry({type:"assistant",message:t,isStreaming:false}),this.lastMessageRole="assistant";}addSupervisorMessage(e){let t={role:"user",content:[{type:"text",text:e}]};this.lastEntryId=this.runtime.addEntry({type:"supervisor",message:t}),this.lastMessageRole="user";}startSupervisorStreaming(){this.startAgentStreaming("Supervisor"),this.streamingSourceLabel="Supervisor",this.streamingSourceType="supervisor";}startExecutorStreaming(e){let t=e||"Executor";this.startAgentStreaming(t);}getStreamingSourceType(){return this.streamingSourceType}startAgentStreaming(e){this.agentBuffers.has(e)||this.agentBuffers.set(e,""),this.activeAgentId=e,this.lastMessageRole="assistant",p.debug("INK_ADAPTER",`Started agent streaming for ${e}`);}startWorkerStreaming(e){this.startAgentStreaming(e);}addWorkerTextDelta(e,t){this.streamText(t,e);}completeWorkerStreaming(e){this.completeTextStreaming(e);}addWorkerInfo(e,t,n,r="info"){let i=`${`[${e}]`} ${t}`,a=r==="error"?"warning":r;this.addInfo(i,n,a);}streamText(e,t){let n=Date.now(),r=t||this.activeAgentId||"default";p.debug("INK_ADAPTER",`streamText: ${e.length} chars to ${r}`,{snippet:e.substring(0,30),bufferExists:this.agentBuffers.has(r)});let o=Date.now()-n;o>10&&p.warn("INK_ADAPTER",`\u26A0\uFE0F streamText slow: ${o}ms for ${e.length} chars`);let i=this.agentBuffers.get(r)||"";this.agentBuffers.set(r,i+e);}addTextDelta(e,t){p.debug("INK_ADAPTER",`addTextDelta called: ${e.length} chars, agentId=${t||"default"}`,{delta:e.substring(0,50)}),this.streamText(e,t);}addAgentTextDelta(e,t,n){p.debug("INK_ADAPTER",`addAgentTextDelta: ${e.length} chars, agentId=${t}`,{delta:e.substring(0,50)}),this.agentBuffers.has(t)||this.agentBuffers.set(t,"");let r=this.agentBuffers.get(t)||"";this.agentBuffers.set(t,r+e);let i={role:"assistant",content:[{type:"text",text:this.agentBuffers.get(t)||""}]};this.runtime.updatePendingEntryByKey(t,{type:"assistant",message:i,isStreaming:true,isComplete:false,sourceLabel:n||t});}bufferAgentTextOnly(e,t){this.agentBuffers.has(t)||this.agentBuffers.set(t,"");let n=this.agentBuffers.get(t)||"";this.agentBuffers.set(t,n+e);}flushAgentBuffer(e){let t=this.agentBuffers.get(e)||"";return this.agentBuffers.delete(e),t}commitPendingEntryByKey(e){return this.agentBuffers.has(e)&&this.agentBuffers.delete(e),this.runtime.commitPendingEntryByKey(e)}addToolCall(e,t){let n={role:"assistant",content:[{type:"tool_use",id:`tool_${Math.floor(Date.now())}`,name:e,input:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_call";}addToolCallEntry(e,t,n){p.debug("INK_ADAPTER","Add tool call entry",{toolName:e,sourceLabel:n?.sourceLabel});let o={read_file:"readfile",Read:"readfile",search:"search",Grep:"search",grep:"search",glob:"search_files",Glob:"search_files",search_files:"search_files",smart_tree:"show_tree",tree:"show_tree",bash:"command_running",Bash:"command_running",shell:"command_running",execute_shell:"command_running",edit:"file_update",Edit:"file_update",write:"file_update",Write:"file_update",web_search:"web_search",WebSearch:"web_search",web_fetch:"web_fetch",WebFetch:"web_fetch",browser:"browser_debug",task:"task",Task:"task"}[e]||"tool_call",i=["bash","Bash","shell","execute_shell"].includes(e),a,l;i&&t.command?(l=`$ ${t.command}`,a="\u23F3 \u6B63\u5728\u6267\u884C\u4E2D..."):(l=e,a=JSON.stringify(t,null,2)),this.runtime.addEntry({type:o,text:l,details:a,isStreaming:i,sourceLabel:n?.sourceLabel});}addToolResult(e,t=false){let n={role:"user",content:[{type:"tool_result",tool_use_id:`tool_${Math.floor(Date.now())}`,content:e,is_error:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_result";}addEntry(e){return p.debug("INK_ADAPTER",`AddEntry: ${e.type}`,{text:e.text}),this.runtime.addEntry(e)}addInfo(e,t,n="info"){p.info("INK_ADAPTER",`Info: ${e}`,t?{details:t}:void 0);let r=n==="warning"||e.includes("\u26A0")||e.includes("\u23F3")||e.includes("\u23F1\uFE0F")||e.includes("\u{1F504}");this.runtime.addEntry({type:r?"warning":"info",text:e,details:t});}addError(e,t){let n=typeof t=="string"?t:t?.details,r=typeof t=="object"?t?.sourceLabel:void 0;p.error("INK_ADAPTER",e,n?{details:n}:void 0),this.runtime.addEntry({type:"error",text:e,details:n,sourceLabel:r});}addWarning(e,t,n){p.warn("INK_ADAPTER",e,t?{details:t}:void 0),this.runtime.addEntry({type:"warning",text:e,details:t,sourceLabel:n?.sourceLabel});}addCompacting(e,t){p.info("INK_ADAPTER",`Compacting: ${e}`,t?{details:t}:void 0),this.runtime.addEntry({type:"compacting",text:e,details:t});}updateStatus(e,t){if(t==="tool_call"&&e.includes("Streaming:")){let n=e.match(/\((\d+) chars\)/);if(n){let r=parseInt(n[1],10);this.streamingToolChars=r,this.runtime.updateStreamingStats(r);}}else t!=="tool_call"&&(this.streamingToolChars=0);t==="compacting"||t==="thinking"||t==="tool_call"?this.runtime.setRunning(true):(t==="complete"||t==="error")&&this.runtime.setRunning(false),this.runtime.setStatusText(e);}setRunning(e){this.runtime.setRunning(e);}startSessionTimer(){}getAccumulatedRunTime(){return this.runtime.getAccumulatedRunTime()}resetAccumulatedRunTime(){this.runtime.resetAccumulatedRunTime();}setCompressionMode(e){this.runtime.setCompressionMode(e);}setCompactionThreshold(e){this.runtime.setCompactionThreshold(e/100);}updateTokenStats(e,t){this.tokenStats.inputTokens=e,this.tokenStats.outputTokens=t,this.tokenStats.totalTokens=e+t,this.runtime.setTokenStats({input:e,output:t,total:e+t});}updateAgentContext(e,t){this.runtime.updateAgentContext(e,t);}clearAgentContext(e){this.runtime.clearAgentContext(e);}clearAllAgentContexts(){this.runtime.clearAllAgentContexts();}getTokenStats(){return {...this.tokenStats}}setTokenStats(e,t,n){p.info("DEBUG_CTX",`InkUIAdapter.setTokenStats: input=${e}, output=${t}, extras.contextWindow=${n?.contextWindow}`),this.tokenStats={inputTokens:e,outputTokens:t,totalTokens:e+t,...n};let r=n?.anthropicCacheCreationTokens||n?.openaiCachedTokens||n?.cacheCreationTokens,o=n?.anthropicCacheReadTokens||n?.cacheReadTokens,i=n?.contextWindow||0,a=n?.tokensUsedForContext||e+t+(o||0),l=i>0?a/i:0;p.info("DEBUG_CTX",`InkUIAdapter.setTokenStats: passing to runtime contextWindow=${n?.contextWindow}, calculated contextWindow=${i}`),this.runtime.setTokenStats({input:e,output:t,total:e+t,contextWindow:n?.contextWindow,tokensUsedForContext:n?.tokensUsedForContext,pressure:l,systemTokens:n?.systemTokens,userTokens:n?.userTokens,assistantTokens:n?.assistantTokens,toolCallTokens:n?.toolCallTokens,toolResultTokens:n?.toolResultTokens,toolTokens:n?.toolTokens,messageTokens:n?.messageTokens,cacheCreationTokens:r,cacheReadTokens:o});}startThinking(){this.streamingReasoningBuffer="",this.streamingReasoningType="thinking";}streamThinking(e,t="thinking"){this.streamingReasoningBuffer+=e,this.streamingReasoningPendingId?this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{text:this.streamingReasoningBuffer}):(this.streamingReasoningType=t,this.streamingReasoningPendingId=this.runtime.addPendingEntry({type:t,text:this.streamingReasoningBuffer,isStreaming:true}));}endThinking(){if(!this.streamingReasoningPendingId){this.updateStatus("","info");return}try{this.streamingReasoningBuffer&&this.streamingReasoningBuffer.trim().length>0?(this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{isStreaming:!1,isComplete:!0}),this.runtime.commitPendingEntry(this.streamingReasoningPendingId),p.debug("INK_ADAPTER",`Committed reasoning entry (${this.streamingReasoningBuffer.length} chars)`)):p.debug("INK_ADAPTER","Discarding empty reasoning entry (no content)");}catch(e){p.warn("INK_ADAPTER","Failed to commit reasoning entry",{error:e});}finally{this.streamingReasoningPendingId=null,this.streamingReasoningBuffer="",this.runtime.resetStreamingStats(),this.updateStatus("","info");}}startTaskTimer(){this.runtime.setRunning(true);}stopTaskTimer(){this.runtime.setRunning(false);}setStreamingTokens(e){this.runtime.updateStreamingStats(e);}clear(){this.runtime.clearMessages(),this.lastMessageRole=null;}resetStreamingState(){this.agentBuffers.clear(),this.activeAgentId=null,this.streamingTextBuffer="",this.streamingTextPendingId=null,this.streamingReasoningBuffer="",this.streamingReasoningPendingId=null,this.currentThinkingText="",this.streamingToolChars=0,this.runtime.clearPendingEntries(),this.runtime.resetStreamingStats(),this.runtime.setStatusText(""),p.debug("INK_ADAPTER","Reset streaming state (cleared all pending entries and buffers)");}finalizeStreamingState(){let e=Array.from(this.agentBuffers.keys());if(e.length>0)for(let t of e)this.completeTextStreaming(t);else this.completeTextStreaming();this.completeReasoningStreaming();}startReasoningStreaming(){this.startThinking();}streamReasoningText(e){this.streamThinking(e);}addReasoningDelta(e){this.streamThinking(e,"reasoning");}completeReasoningStreaming(){this.endThinking();}addThinking(e){}completeTextStreaming(e){let t=e||this.activeAgentId||"default",n=this.agentBuffers.get(t)||"";if(!(n&&n.trim().length>0)){p.debug("INK_ADAPTER",`Complete text streaming (${t}) - no text to commit`),this.agentBuffers.delete(t),this.runtime.commitPendingEntryByKey(t),(t==="default"||t===this.activeAgentId)&&(this.streamingTextPendingId=null,this.streamingSourceLabel=null,this.streamingSourceType=null,this.runtime.resetStreamingStats());return}try{if(this.runtime.commitPendingEntryByKey(t))p.debug("INK_ADAPTER",`Complete text streaming (${t}) - committed pending entry ${n.length} chars`);else {let i={role:"assistant",content:[{type:"text",text:n}]};this.runtime.addEntry({type:"assistant",message:i,isStreaming:!1,isComplete:!0,sourceLabel:t==="default"?void 0:t}),p.debug("INK_ADAPTER",`Complete text streaming (${t}) - created static entry from buffer ${n.length} chars`);}}catch(o){p.warn("INK_ADAPTER","Failed to commit text entry",{error:o});}finally{this.agentBuffers.delete(t),(t==="default"||t===this.activeAgentId)&&(this.streamingTextPendingId=null,this.streamingSourceLabel=null,this.streamingSourceType=null,this.lastMessageRole="assistant",this.runtime.resetStreamingStats()),this.activeAgentId===t&&(this.activeAgentId=null);}}printCommandOutput(e){p.debug("INK_ADAPTER",`Command output: ${e}`);}setCommandOutputLines(e){p.debug("INK_ADAPTER",`Set command output lines: ${e.length}`),this.runtime.setCommandOutput(e);}clearCommandOutputLines(){p.debug("INK_ADAPTER","Clear command output lines"),this.runtime.clearCommandOutput();}startToolCallWithId(e,t,n,r){p.debug("INK_ADAPTER",`Start tool call: ${t}`,{toolId:e,args:n});let o=this.buildToolCallDetails(n,r),i=r?.sourceLabel,c={readfile:"readfile",Read:"readfile",read_file:"readfile",search:"search",Grep:"search",grep:"search",search_files:"search_files",Glob:"search_files",glob:"search_files",find_files:"search_files",show_tree:"show_tree",smart_tree:"show_tree",list_directory:"show_tree",ls:"show_tree",file_update:"file_update",Edit:"file_update",edit_file:"file_update",Write:"file_update",write_file:"file_update",command_exec:"command_exec",Bash:"command_exec",bash:"command_exec",shell:"command_exec",execute_command:"command_exec",code_exec:"code_exec",web_search:"web_search",WebSearch:"web_search",web_fetch:"web_fetch",WebFetch:"web_fetch",browser_debug:"browser_debug",TodoWrite:"todo",TodoRead:"todo",Task:"task",NotebookEdit:"notebook",NotebookRead:"notebook",AskUserQuestion:"ask_user"}[t]||"tool_call",u=this.runtime.addEntry({type:c,text:t,details:o,isStreaming:true,sourceLabel:i});this.toolLogIdByToolId.set(e,u),this.toolLogDetailsByToolId.set(e,o||""),this.toolLogNameByToolId.set(e,t),i&&this.toolLogSourceLabelByToolId.set(e,i);}updateToolCallOutput(e,t,n){p.debug("INK_ADAPTER",`Update tool output: ${e}`,{output:t});let r=this.toolLogIdByToolId.get(e);if(!r)return;let o=this.toolLogDetailsByToolId.get(e)||"",i=this.formatToolOutput(t,n?.truncated);i&&this.toolLogOutputByToolId.set(e,i);let a=this.mergeToolDetails(o,i);this.runtime.updateEntry(r,{details:a,isStreaming:true});}completeToolCall(e,t){p.debug("INK_ADAPTER",`Complete tool call: ${e}`);let n=this.toolLogIdByToolId.get(e);if(!n){t?.result&&this.addToolResult(t.result,t.isError||false);return}let r=this.toolLogNameByToolId.get(e)||"",o=this.toolLogDetailsByToolId.get(e)||"",i=this.toolLogOutputByToolId.get(e)||"",a=this.toolLogSourceLabelByToolId.get(e),l=t?.summary||t?.error||"",c=[];o&&c.push(o),l&&c.push(l),!l&&i&&c.push(i),typeof t?.duration=="number"&&c.push(`duration: ${this.formatDuration(t.duration)}`),typeof t?.resultLength=="number"&&c.push(`result: ${t.resultLength}B`);let u=c.length>0?c.join(`
|
|
1683
|
+
`):[s];return I.createElement(S,{flexDirection:"column"},I.createElement(S,{flexDirection:n?"column":"row"},!n&&I.createElement(y,{color:"green",bold:true},"> "),t?I.createElement(y,{dimColor:true},s||e):!s?I.createElement(S,null,!n&&I.createElement(y,{inverse:true}," "),I.createElement(y,{dimColor:true},e)):n?z.map((O,F)=>I.createElement(S,{key:F},I.createElement(y,{color:"green",bold:true},F===0?"> ":"\u2502 "),I.createElement(y,null,O))):I.createElement(y,null,_,I.createElement(y,{inverse:true},P),j)),f&&r.length>0&&I.createElement(S,{paddingLeft:2,flexDirection:"column"},I.createElement(y,{color:"yellow"},"Suggestions:"),r.slice(0,5).map((O,F)=>I.createElement(y,{key:F,color:F===b?"cyan":"white",bold:F===b},F===b?"\u2192 ":" ",O))))};var N_=({isRunning:s,statusText:e="",tokenStats:t,streamingTokens:n=0,streamingStartTime:r=null,provider:o,model:i,onContextMenuToggle:a,agentContextStats:l=[],maxDisplayAgents:c=3,runMode:u="single",networkStats:d,cooperateStats:m})=>{let[g,h]=useState(null),[f,v]=useState(0),[b,C]=useState(0),[T,w]=useState(0),[E,N]=useState(0);useEffect(()=>{s?(h(r||Date.now()),v(0)):!s&&(t?.output||0)===0&&(h(null),v(0));},[s,r,t?.output]),useEffect(()=>{if(!s||g===null)return;let V=setInterval(()=>{v(Math.floor((Date.now()-g)/1e3));},500);return ()=>clearInterval(V)},[s,g]),useEffect(()=>{if(!s||n===0){C(0);return}let V=Math.floor(n);if(b===V)return;let re=V-b,ue=Math.min(Math.abs(re),20),se=re/ue,ee=setInterval(()=>{C(ve=>{let L=ve+se;return Math.abs(L-V)<1?V:L});},50);return ()=>clearInterval(ee)},[n,s,b]),useEffect(()=>{let V=t?.output||0;if(T===V)return;let re=V-T;if(Math.abs(re)>100){w(V);return}let ue=Math.max(Math.ceil(Math.abs(re)/10),3),se=re/ue,ee=setInterval(()=>{w(ve=>{let L=ve+se;return Math.abs(L-V)<1?V:L});},10);return ()=>clearInterval(ee)},[t?.output,T]),useEffect(()=>{if(!s){N(0);return}let re=(e||"Thinking...").length,ue=setInterval(()=>{N(se=>(se+1)%(re+3));},80);return ()=>clearInterval(ue)},[s,e]);let D=()=>{if(f<60)return `${f}s`;let V=Math.floor(f/60),re=f%60;return `${V}m ${re}s`},$=V=>V>=1e6?(V/1e6).toFixed(1)+"M":V>=1e3?(V/1e3).toFixed(1)+"K":V.toString(),k=t?.contextWindow||0,M=t?.tokensUsedForContext||t?.total||0,_=t?.pressure||0,P=Math.round(_*100),j=()=>_>.8?"red":_>.5?"yellow":"green",z=V=>V.split("").map((ue,se)=>{let ae=se-E;return ae>=0&&ae<2?I.createElement(y,{key:se,color:"white",bold:true},ue):ae>=-1&&ae<0?I.createElement(y,{key:se,color:"cyanBright"},ue):I.createElement(y,{key:se,color:"cyan"},ue)}),O=(()=>{switch(u){case "single":return {icon:"\u{1F464}",label:"Single",color:"cyan"};case "collab":return {icon:"\u{1F91D}",label:"Collab",color:"magenta"};case "cooperate":return {icon:"\u{1F527}",label:"Cooperate",color:"yellow"};case "network":return {icon:"\u{1F310}",label:"Network",color:"blue"};default:return {icon:"\u{1F464}",label:"Single",color:"cyan"}}})(),F=e&&(e.includes("Streaming:")||e.toLowerCase().includes("stream")),U=e?.match(/Streaming:\s*(\w+)/),K=U?U[1]:null,de=l.length>0,W=l.find(V=>V.agentId==="Main"),H=l.filter(V=>V.agentId!=="Main"),ne=H.length>c,J=()=>H.length===0?null:I.createElement(S,null,I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"magenta"},H.length),I.createElement(y,{dimColor:true}," workers"),ne&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2022 Ctrl+G"))),fe=(V,re)=>{let ue=V.pressure||0,se=Math.round(ue*100),ae=()=>ue>.8?"red":ue>.5?"yellow":"green",ee=()=>{switch(V.status||"idle"){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},{icon:ve,color:L}=ee(),q=V.currentTask?V.currentTask.length>20?V.currentTask.slice(0,17)+"...":V.currentTask:"";return I.createElement(S,{key:V.agentId,justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{dimColor:true},re?"\u2514\u2500 ":"\u251C\u2500 "),I.createElement(y,{color:L},ve),I.createElement(y,null," "),I.createElement(y,{color:"magenta"},V.agentLabel),q&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{dimColor:true},q))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(V.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(V.output)),I.createElement(y,{dimColor:true}," \u2502 context "),I.createElement(y,{color:"yellow"},$(V.tokensUsedForContext)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},$(V.contextWindow)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:ae()},se,"%"),I.createElement(y,{dimColor:true},")")))};if(u==="network"){let V=d?.teamSize||0,re=d?.activeAgents||0,ue=d?.currentPhase||"executing",se=d?.currentAgent,ae=d?.totalInputTokens||t?.input||0,ee=d?.totalOutputTokens||t?.output||0,ve=d?.completedTasks,L=d?.totalTasks,Q=(()=>{switch(ue){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})();return I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"blue"},"\u{1F310}"),I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"blue"},V),I.createElement(y,{dimColor:true}," agents"),re>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"green"},re),I.createElement(y,{dimColor:true}," active)")),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),se?I.createElement(I.Fragment,null,z(se),I.createElement(y,{dimColor:true},": "),I.createElement(y,{color:Q.color},Q.text)):I.createElement(y,{color:Q.color},Q.text),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(S,null,ee>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,ve!==void 0&&L!==void 0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true},"tasks "),I.createElement(y,{color:"yellow"},ve),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},L),I.createElement(y,{dimColor:true}," \u2502 ")),s&&b>0&&I.createElement(I.Fragment,null,I.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),I.createElement(y,{dimColor:true}," \u2502 ")),I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(ae)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(ee))))}if(u==="cooperate"&&m){let{models:V,phase:re,totalInputTokens:ue,totalOutputTokens:se,ccbResult:ae,dagProgress:ee}=m,L=(()=>{switch(re){case "analyzing":return {text:"Analyzing",color:"cyan"};case "ccb_review":return {text:"CCB Review",color:"yellow"};case "dag_planning":return {text:"Planning",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})(),q=()=>V.length===0?null:V.map((le,Ee)=>{let Pe=le.status==="running"?"green":le.status==="completed"?"blue":"gray";return I.createElement(I.Fragment,{key:Ee},Ee>0&&I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:Pe},le.shortName))}),Q=V.filter(le=>le.status==="completed").length;return I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"yellow"},"\u{1F527}"),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),e?z(e):I.createElement(y,{color:L.color},L.text),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")")),b>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ~"),I.createElement(y,{color:"magenta"},Math.floor(b)),I.createElement(y,{dimColor:true}," tok"))):I.createElement(S,null,se>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,V.length>0&&I.createElement(I.Fragment,null,q(),I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:"yellow"},Q),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},V.length),I.createElement(y,{dimColor:true}," \u2502 ")),ae&&I.createElement(I.Fragment,null,I.createElement(y,{color:ae.approved?"green":"red"},ae.approved?"\u2713":"\u2717"),I.createElement(y,{dimColor:true}," CCB "),I.createElement(y,{color:"yellow"},ae.approveCount),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},ae.totalCount),I.createElement(y,{dimColor:true}," \u2502 ")),ee&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true},"DAG "),I.createElement(y,{color:"yellow"},ee.completedNodes),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},ee.totalNodes),I.createElement(y,{dimColor:true}," \u2502 ")),I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(ue||t?.input||0)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(se||t?.output||0))))}if((u==="collab"||u==="cooperate")&&de){let V=W?.pressure||0,re=Math.round(V*100),ue=()=>V>.8?"red":V>.5?"yellow":"green",se=H.length<=c&&H.length>0,ae=W?.agentLabel||"Main";return I.createElement(S,{flexDirection:"column"},I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:O.color},O.icon),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),I.createElement(y,{bold:true,color:"cyan"},"\u25CF"),I.createElement(y,null," "),F&&K?I.createElement(I.Fragment,null,z(`Streaming: ${K}`)):z(e||"Thinking..."),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(S,null,(W?.output||t?.output||0)>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,W?I.createElement(S,null,I.createElement(y,{dimColor:true},ae,": "),I.createElement(y,{color:"cyan"},$(W.input)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"green"},$(W.output)),(W.cacheCreationTokens||W.cacheReadTokens)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," cache-w "),I.createElement(y,{color:"magenta"},$(W.cacheCreationTokens||0)),I.createElement(y,{dimColor:true}," cache-r "),I.createElement(y,{color:"blue"},$(W.cacheReadTokens||0))),I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"yellow"},$(W.tokensUsedForContext)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},$(W.contextWindow)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:ue()},re,"%"),I.createElement(y,{dimColor:true},")"),J()):I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(t?.input||0)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(t?.output||0)),J()))),se&&H.map((ee,ve)=>fe(ee,ve===H.length-1)))}return I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:O.color},O.icon),I.createElement(y,{dimColor:true}," \u2502 "),s?I.createElement(S,null,I.createElement(vl,{type:"dots"}),I.createElement(y,null," "),I.createElement(y,{bold:true,color:"cyan"},"\u25CF"),I.createElement(y,null," "),F&&K?I.createElement(I.Fragment,null,z(`Streaming: ${K}`)):z(e||"Thinking..."),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true}," \u2022 esc to interrupt"),b>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2022 "),I.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),I.createElement(y,{dimColor:true}," ",F?"chars":"tokens")),I.createElement(y,{dimColor:true},")"))):I.createElement(S,null,(t?.output||0)>0?I.createElement(I.Fragment,null,I.createElement(y,{color:"green",bold:true},"\u25A0"),I.createElement(y,null," "),I.createElement(y,{color:"green"},"Complete!"),f>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"yellow"},D()),I.createElement(y,{dimColor:true},")"))):I.createElement(I.Fragment,null,I.createElement(y,{color:"cyan",bold:true},"\u25CF"),I.createElement(y,null," "),I.createElement(y,{color:"cyan"},"Ready")))),I.createElement(S,null,k>0?I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},$(t?.input||0)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},$(t?.output||0)),(t?.cacheCreationTokens||t?.cacheReadTokens)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," cache-w "),I.createElement(y,{color:"magenta"},$(t.cacheCreationTokens||0)),I.createElement(y,{dimColor:true}," cache-r "),I.createElement(y,{color:"blue"},$(t.cacheReadTokens||0))),I.createElement(y,{dimColor:true}," \u2502 context "),I.createElement(y,{color:"yellow"},$(M)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},$(k)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:j()},P,"%"),I.createElement(y,{dimColor:true},")")):I.createElement(y,{dimColor:true},"context: --")))},L_=(s,e)=>!s&&!e?true:!s||!e||s.length!==e.length?false:s.every((t,n)=>{let r=e[n];return t.agentId===r.agentId&&t.input===r.input&&t.output===r.output&&t.pressure===r.pressure&&t.tokensUsedForContext===r.tokensUsedForContext&&t.status===r.status&&t.currentTask===r.currentTask&&t.contextWindow===r.contextWindow&&t.cacheCreationTokens===r.cacheCreationTokens&&t.cacheReadTokens===r.cacheReadTokens}),Py=I.memo(N_,(s,e)=>s.isRunning===e.isRunning&&s.statusText===e.statusText&&s.streamingTokens===e.streamingTokens&&s.streamingStartTime===e.streamingStartTime&&s.tokenStats?.input===e.tokenStats?.input&&s.tokenStats?.output===e.tokenStats?.output&&s.tokenStats?.total===e.tokenStats?.total&&s.tokenStats?.pressure===e.tokenStats?.pressure&&s.tokenStats?.cacheCreationTokens===e.tokenStats?.cacheCreationTokens&&s.tokenStats?.cacheReadTokens===e.tokenStats?.cacheReadTokens&&s.runMode===e.runMode&&s.networkStats?.teamSize===e.networkStats?.teamSize&&s.networkStats?.activeAgents===e.networkStats?.activeAgents&&s.networkStats?.currentPhase===e.networkStats?.currentPhase&&s.networkStats?.currentAgent===e.networkStats?.currentAgent&&s.networkStats?.totalInputTokens===e.networkStats?.totalInputTokens&&s.networkStats?.totalOutputTokens===e.networkStats?.totalOutputTokens&&s.networkStats?.completedTasks===e.networkStats?.completedTasks&&s.networkStats?.totalTasks===e.networkStats?.totalTasks&&s.cooperateStats?.phase===e.cooperateStats?.phase&&s.cooperateStats?.totalInputTokens===e.cooperateStats?.totalInputTokens&&s.cooperateStats?.totalOutputTokens===e.cooperateStats?.totalOutputTokens&&s.cooperateStats?.ccbResult?.approved===e.cooperateStats?.ccbResult?.approved&&s.cooperateStats?.ccbResult?.approveCount===e.cooperateStats?.ccbResult?.approveCount&&s.cooperateStats?.dagProgress?.completedNodes===e.cooperateStats?.dagProgress?.completedNodes&&s.cooperateStats?.models?.length===e.cooperateStats?.models?.length&&L_(s.agentContextStats,e.agentContextStats));var Ry=({isRunning:s,hasInput:e,customHints:t,menuActive:n=false,thinkingEnabled:r=true,accumulatedRunTime:o=0,provider:i,model:a,runMode:l="single"})=>{let[c,u]=useState(o);useEffect(()=>{if(!s){u(o);return}u(o);let f=setInterval(()=>{u(v=>v+1);},1e3);return ()=>clearInterval(f)},[s,o]);let d=()=>{if(c<60)return `${c}s`;let f=Math.floor(c/60),v=c%60;if(f<60)return `${f}m ${v}s`;let b=Math.floor(f/60),C=f%60;return `${b}h ${C}m`},m=()=>{if(!i||!a)return "";let f=i,v=i.indexOf(" (");v>0&&(f=i.substring(0,v));let b=a.length>35?a.substring(0,32)+"...":a;return `${f}/${b}`},h=(()=>{switch(l){case "single":return {label:"SINGLE",color:"cyan"};case "collab":return {label:"COLLAB",color:"magenta"};case "cooperate":return {label:"COOPERATE",color:"yellow"};case "network":return {label:"NETWORK",color:"blue"};default:return {label:"SINGLE",color:"cyan"}}})();return t?I.createElement(S,{justifyContent:"space-between"},I.createElement(y,{color:"yellow"},t)):n?I.createElement(S,{justifyContent:"space-between"},I.createElement(y,{dimColor:true}," ","\u2191\u2193 to select, Enter to confirm, ESC to cancel")):I.createElement(S,{justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{dimColor:true},"? for shortcuts"),c>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2022 "),I.createElement(y,{color:"cyan"},d()),I.createElement(y,{dimColor:true}," session"))),I.createElement(S,null,I.createElement(y,{color:h.color,bold:true},"["),I.createElement(y,{color:h.color},h.label),I.createElement(y,{color:h.color,bold:true},"]"),I.createElement(y,{dimColor:true}," \u2022 "),m()&&I.createElement(I.Fragment,null,I.createElement(y,{color:"magenta",bold:true},"["),I.createElement(y,{color:"magenta"},m()),I.createElement(y,{color:"magenta",bold:true},"]"),I.createElement(y,{dimColor:true}," \u2022 ")),r?I.createElement(y,{color:"cyan"},"Thinking on"):I.createElement(y,{dimColor:true},"Thinking off"),I.createElement(y,{dimColor:true}," (tab to toggle)")))};var Dy=({attachments:s,onRemove:e})=>s.length===0?null:I.createElement(S,{flexDirection:"column",paddingLeft:2,marginBottom:1},I.createElement(y,{color:"magenta",dimColor:true},"Attachments:"),s.map((t,n)=>{let r=t.name||t.path?.split("/").pop()||"unknown",o=t.type?.startsWith("image/")||t.mediaType?.startsWith("image/")||r.match(/\.(png|jpg|jpeg|gif|webp)$/i);return I.createElement(S,{key:n},I.createElement(y,{color:"magenta"},o?"\u{1F4CE} \u{1F5BC}\uFE0F ":"\u{1F4CE} ",r),e&&I.createElement(y,{color:"gray",dimColor:true}," (press \u232B Backspace to remove)"))}));var Ny=({contextWindow:s,tokensUsed:e,systemTokens:t=0,userTokens:n=0,assistantTokens:r=0,toolCallTokens:o=0,toolResultTokens:i=0,compactionThreshold:a=.8,compressionMode:l="sync",agentContextStats:c=[],runMode:u="single",networkStats:d,onClose:m})=>{let g=D=>D>=1e6?`${(D/1e6).toFixed(1)}M`:D>=1e3?`${(D/1e3).toFixed(1)}k`:D.toString(),h=D=>D>.8?"red":D>.5?"yellow":"green",f=({color:D,label:$,tokens:k,total:M,indent:_=2})=>{let P=M>0?(k/M*100).toFixed(2):"0.00";return I.createElement(S,{marginLeft:_},I.createElement(y,{color:D},"\u25A0"),I.createElement(y,null," ",$,": "),I.createElement(y,{color:"yellow"},g(k)),I.createElement(y,{dimColor:true}," tokens (",P,"%)"))},v=({stat:D,indent:$=2})=>{let k=D.cacheCreationTokens||0,M=D.cacheReadTokens||0,_=D.contextWindow||2e5,P=D.tokensUsedForContext||0,j=_>0?P/_:0,z=Math.round(j*100);return I.createElement(S,{marginLeft:$,justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"magenta"},D.agentLabel||D.agentId),D.status&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:D.status==="running"?"green":D.status==="error"?"red":"gray"},D.status==="running"?"\u25CF":D.status==="completed"?"\u2713":D.status==="error"?"\u2717":"\u25CB"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},g(D.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},g(D.output)),(k>0||M>0)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," \u2502 cw "),I.createElement(y,{color:"blue"},g(k)),I.createElement(y,{dimColor:true}," cr "),I.createElement(y,{color:"blue"},g(M))),I.createElement(y,{dimColor:true}," \u2502 ctx "),I.createElement(y,{color:"yellow"},g(P)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},g(_)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:h(j)},z,"%"),I.createElement(y,{dimColor:true},")")))},b=({stat:D,indent:$=2})=>{let k=D.contextWindow>0?D.tokensUsedForContext/D.contextWindow:0,M=Math.round(k*100);return I.createElement(S,{marginLeft:$,justifyContent:"space-between"},I.createElement(S,null,I.createElement(y,{color:"magenta"},D.agentLabel||D.agentId),D.status&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:D.status==="running"?"green":D.status==="error"?"red":"gray"},D.status==="running"?"\u25CF":D.status==="completed"?"\u2713":D.status==="error"?"\u2717":"\u25CB"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},g(D.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},g(D.output)),I.createElement(y,{dimColor:true}," \u2502 "),I.createElement(y,{color:"yellow"},g(D.tokensUsedForContext)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},g(D.contextWindow)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:h(k)},M,"%"),I.createElement(y,{dimColor:true},")")))};if(u==="network"){let D=d?.teamSize||c.length||0,$=d?.activeAgents||0,k=d?.totalInputTokens||0,M=d?.totalOutputTokens||0,_=k+M,j=(z=>{switch(z){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Idle",color:"gray"}}})(d?.currentPhase);return I.createElement(S,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1},I.createElement(S,{justifyContent:"space-between",marginBottom:1},I.createElement(S,null,I.createElement(y,{color:"blue"},"\u{1F310}"),I.createElement(y,{bold:true,color:"blue"}," Network Context Overview")),I.createElement(y,{dimColor:true},"(press ESC to close)")),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Team Size: "),I.createElement(y,{color:"blue",bold:true},D),I.createElement(y,{dimColor:true}," agents"),$>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"green"},$),I.createElement(y,{dimColor:true}," active)"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"Current Phase: "),I.createElement(y,{color:j.color,bold:true},j.text),d?.currentAgent&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," - "),I.createElement(y,{color:"cyan"},d.currentAgent))),d?.completedTasks!==void 0&&d?.totalTasks!==void 0&&I.createElement(S,null,I.createElement(y,{dimColor:true},"Tasks: "),I.createElement(y,{color:"yellow"},d.completedTasks),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},d.totalTasks),I.createElement(y,{dimColor:true}," completed"))),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(y,{bold:true,dimColor:true},"Total Token Usage:"),I.createElement(S,{marginLeft:2},I.createElement(y,{dimColor:true},"Input: "),I.createElement(y,{color:"cyan"},g(k)),I.createElement(y,{dimColor:true}," \u2502 Output: "),I.createElement(y,{color:"green"},g(M)),I.createElement(y,{dimColor:true}," \u2502 Total: "),I.createElement(y,{color:"yellow"},g(_)))),c.length>0&&I.createElement(S,{flexDirection:"column"},I.createElement(y,{bold:true,dimColor:true},"Agent Context Details:"),c.map(z=>I.createElement(v,{key:z.agentId,stat:z})),I.createElement(S,{marginTop:1,marginLeft:2},I.createElement(y,{dimColor:true},"Total Tokens: "),I.createElement(y,{color:"yellow"},g(c.reduce((z,A)=>z+A.input+A.output,0))),I.createElement(y,{dimColor:true}," across "),I.createElement(y,{color:"cyan"},c.length),I.createElement(y,{dimColor:true}," agents"))),c.length===0&&I.createElement(S,{marginTop:1},I.createElement(y,{dimColor:true,italic:true},"Agent context details not available yet.")))}if((u==="collab"||u==="cooperate")&&c.length>0){let D=c.find(A=>A.agentId==="Main"),$=c.filter(A=>A.agentId!=="Main"&&A.agentId!=="supervisor"),k=c.reduce((A,O)=>A+O.tokensUsedForContext,0),M=c.reduce((A,O)=>A+O.input,0),_=c.reduce((A,O)=>A+O.output,0),P=u==="collab"?"\u{1F91D}":"\u{1F527}",j=u==="collab"?"Collab":"Cooperate",z=u==="collab"?"magenta":"yellow";return I.createElement(S,{flexDirection:"column",borderStyle:"round",borderColor:z,paddingX:2,paddingY:1},I.createElement(S,{justifyContent:"space-between",marginBottom:1},I.createElement(S,null,I.createElement(y,{color:z},P),I.createElement(y,{bold:true,color:z}," ",j," Context Overview")),I.createElement(y,{dimColor:true},"(press ESC to close)")),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Total Agents: "),I.createElement(y,{color:z,bold:true},c.length),$.length>0&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," (1 Main + "),I.createElement(y,{color:"cyan"},$.length),I.createElement(y,{dimColor:true}," Workers)"))),I.createElement(S,null,I.createElement(y,{dimColor:true},"Total Tokens: "),I.createElement(y,{color:"cyan"},g(M)),I.createElement(y,{dimColor:true}," in / "),I.createElement(y,{color:"green"},g(_)),I.createElement(y,{dimColor:true}," out"))),D&&I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(y,{bold:true,dimColor:true},"Main Agent:"),I.createElement(b,{stat:D})),$.length>0&&I.createElement(S,{flexDirection:"column"},I.createElement(y,{bold:true,dimColor:true},"Worker Agents (",$.length,"):"),$.map(A=>I.createElement(b,{key:A.agentId,stat:A}))),I.createElement(S,{marginTop:1},I.createElement(y,{dimColor:true},"Combined Context: "),I.createElement(y,{color:"yellow"},g(k)),I.createElement(y,{dimColor:true}," tokens")))}let C=s-e,T=s>0?e/s:0,w=Math.floor(s*a),E=Math.max(0,w-e),N=Math.round(T*100);return I.createElement(S,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},I.createElement(S,{justifyContent:"space-between",marginBottom:1},I.createElement(y,{bold:true,color:"cyan"},"Context Window Details"),I.createElement(y,{dimColor:true},"(press ESC to close)")),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Total: "),I.createElement(y,{color:"yellow"},g(e)),I.createElement(y,{dimColor:true}," / "),I.createElement(y,{color:"yellow"},g(s)),I.createElement(y,{dimColor:true}," tokens ("),I.createElement(y,{color:h(T),bold:true},N,"%"),I.createElement(y,{dimColor:true},")")),I.createElement(S,null,I.createElement(y,{dimColor:true},"Remaining: "),I.createElement(y,{color:"green"},g(C)),I.createElement(y,{dimColor:true}," tokens"))),I.createElement(S,{flexDirection:"column",marginBottom:1},I.createElement(S,null,I.createElement(y,{dimColor:true},"Compression: "),I.createElement(y,{color:l==="sync"?"green":"yellow"},l==="sync"?"Sync LLM":"Async LLM"),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:"cyan"},Math.round(a*100),"%"),I.createElement(y,{dimColor:true}," threshold)"))),E>0?I.createElement(S,{marginBottom:1},I.createElement(y,{dimColor:true},"Compaction in: "),I.createElement(y,{color:"cyan"},g(E)),I.createElement(y,{dimColor:true}," tokens")):I.createElement(S,{marginBottom:1},I.createElement(y,{color:"red",bold:true},"\u26A0\uFE0F Compaction threshold reached!")),I.createElement(S,{flexDirection:"column"},I.createElement(y,{bold:true,dimColor:true},"Context Breakdown:"),I.createElement(f,{color:"magenta",label:"System",tokens:t,total:e}),I.createElement(f,{color:"cyan",label:"User",tokens:n,total:e}),I.createElement(f,{color:"green",label:"Assistant",tokens:r,total:e}),I.createElement(f,{color:"blue",label:"Tool Calls",tokens:o,total:e}),I.createElement(f,{color:"yellow",label:"Tool Results",tokens:i,total:e}),I.createElement(S,{marginTop:1,marginLeft:2},I.createElement(y,{dimColor:true},"Usage: "),I.createElement(y,{color:h(T)},"\u2588".repeat(Math.floor(T*20))),I.createElement(y,{dimColor:true},"\u2591".repeat(20-Math.floor(T*20))))))};Z();var B_=({inputValue:s,isRunning:e,statusText:t="",tokenStats:n,streamingTokens:r=0,streamingStartTime:o=null,accumulatedRunTime:i=0,provider:a,model:l,customHints:c,attachments:u=[],multiline:d=false,completions:m=[],menuActive:g=false,promptActive:h=false,promptMessage:f,promptHint:v,promptOnCancel:b,thinkingEnabled:C=true,contextMenuActive:T=false,compressionMode:w="sync",compactionThreshold:E=.85,agentContextStats:N=[],runMode:D="single",networkStats:$,cooperateStats:k,onInputChange:M,onSubmit:_,onInterrupt:P,onExit:j,onHistoryUp:z,onHistoryDown:A,onTabComplete:O,onRemoveAttachment:F,onContextMenuToggle:U,onAgentContextScreenToggle:K,onPasteImage:de,onShowInterruptInput:W})=>{let{columns:H}=Co();return et((ne,J)=>{if(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","BottomBar useInput",{key:J,input:ne,menuActive:g,promptActive:h,isRunning:e,inputValue:s.substring(0,20)}),!g){if(e&&ne==="i"&&!J.ctrl&&!J.meta&&W){p.debug("INK_INPUT",'Interrupt input triggered with "i" key'),W();return}if(J.ctrl&&ne==="g"&&K){K();return}if(J.ctrl&&ne==="z"){process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+Z blocked (prevents suspension)");return}if(J.escape){let fe=!ne||ne==="\x1B"||ne==="";if(p.info("INK_INPUT",`ESC detected: isRealEscape=${fe}, input=${JSON.stringify(ne)}, isRunning=${e}`),!fe){p.debug("INK_INPUT","Ignoring escape sequence (not real ESC key)");return}if(T&&U){U();return}if(h&&b){b(),M("");return}e?(p.info("INK_INPUT","\u{1F6D1} User pressed ESC to interrupt task"),P()):s&&M("");return}J.ctrl&&ne==="c"&&(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+C pressed",{isRunning:e}),e?P():(p.info("INK_INPUT","\u26A0\uFE0F Ctrl+C pressed - exiting"),j()));}},{isActive:true}),I.createElement(S,{flexDirection:"column"},h&&f&&I.createElement(S,{paddingX:2,paddingY:1},I.createElement(y,{color:"cyan",bold:true},f)),h&&v&&I.createElement(S,{paddingX:2,paddingBottom:1},I.createElement(y,{dimColor:true},v)),!h&&I.createElement(Py,{isRunning:e,statusText:t,tokenStats:n,streamingTokens:r,streamingStartTime:o,provider:a,model:l,onContextMenuToggle:U,agentContextStats:N,runMode:D,networkStats:$,cooperateStats:k}),u.length>0&&I.createElement(Dy,{attachments:u,onRemove:F}),I.createElement(S,{flexDirection:"column"},I.createElement(y,{color:"gray"},"\u2500".repeat(H)),I.createElement(My,{value:s,placeholder:h?v||"Type your answer...":e?"Enter to interrupt and send...":"Type a message...",disabled:g,multiline:d,completions:m,menuActive:g,imageCount:u.length,onChange:M,onSubmit:()=>_(s),onHistoryUp:z,onHistoryDown:A,onTabComplete:O,onPasteImage:de}),I.createElement(y,{color:"gray"},"\u2500".repeat(H))),!h&&I.createElement(Ry,{isRunning:e,hasInput:s.length>0,customHints:c,menuActive:g,thinkingEnabled:C,accumulatedRunTime:i,provider:a,model:l,runMode:D}),T&&n?.contextWindow&&U&&I.createElement(Ny,{contextWindow:n.contextWindow,tokensUsed:n.tokensUsedForContext||n.total,systemTokens:n.systemTokens,userTokens:n.userTokens,assistantTokens:n.assistantTokens,toolCallTokens:n.toolCallTokens,toolResultTokens:n.toolResultTokens,compressionMode:w,compactionThreshold:E,agentContextStats:N,runMode:D,networkStats:$,onClose:U}))},Ly=I.memo(B_);var Yd=({message:s,choices:e,initialIndex:t=0,hint:n,maxVisible:r=20,onSelect:o,onCancel:i,onExit:a})=>{let[l,c]=useState(t),[u,d]=useState(0),[m,g]=useState(null);useEffect(()=>{c(t);},[t]),useEffect(()=>{let b=setTimeout(()=>{g(Date.now());},200);return ()=>clearTimeout(b)},[]),useEffect(()=>{if(e.length<=r){d(0);return}l<u?d(l):l>=u+r&&d(l-r+1);},[l,e.length,r,u]),et((b,C)=>{if(C.ctrl&&b==="c"&&a){process.nextTick(()=>a());return}if(C.escape&&i){process.nextTick(()=>i());return}if(C.upArrow){c(T=>T>0?T-1:e.length-1);return}if(C.downArrow){c(T=>T<e.length-1?T+1:0);return}if(C.return){if(!m)return;process.nextTick(()=>o(e[l].value));return}});let h=Math.min(e.length,r),f=u>0,v=u+h<e.length;return I.createElement(S,{flexDirection:"column"},s&&I.createElement(S,{marginBottom:1,paddingX:2},I.createElement(y,{bold:true,color:"cyan"},s)),n&&I.createElement(S,{marginBottom:1,paddingX:2},I.createElement(y,{dimColor:true},n)),f&&I.createElement(S,{paddingX:2},I.createElement(y,{dimColor:true}," \u2191 more")),e.slice(u,u+h).map((b,C)=>{let T=u+C,w=T===l,E=w?"\u276F ":" ";return I.createElement(S,{key:`${b.value}-${T}`,flexDirection:"row",paddingX:2},I.createElement(y,{color:w?"cyan":void 0,bold:w},E,b.label),b.description&&I.createElement(y,{dimColor:true}," - ",b.description))}),v&&I.createElement(S,{paddingX:2},I.createElement(y,{dimColor:true}," \u2193 more")))};var $y=({onSubmit:s,onCancel:e})=>{let[t,n]=useState(""),[r,o]=useState(0),i=t.length-r;et((u,d)=>{if(d.escape){e();return}if(d.return){let m=t.trim();m&&s(m);return}if(d.backspace||d.delete){if(r===t.length)return;let m=i-1,g=t.slice(0,m)+t.slice(m+1);n(g);return}if(d.leftArrow){o(Math.min(r+1,t.length));return}if(d.rightArrow){o(Math.max(r-1,0));return}if(d.home||d.ctrl&&u==="a"){o(t.length);return}if(d.end||d.ctrl&&u==="e"){o(0);return}if(!d.ctrl&&!d.meta&&u){let m=t.slice(0,i)+u+t.slice(i);n(m);return}},{isActive:true});let a=t.slice(0,i),l=t[i]||" ",c=t.slice(i+1);return I.createElement(S,{flexDirection:"column",borderStyle:"double",borderColor:"yellow",paddingX:2,paddingY:1,width:"80%"},I.createElement(S,{marginBottom:1,justifyContent:"center"},I.createElement(y,{bold:true,color:"yellow"},"\u2728 \u63D2\u961F\u6D88\u606F - \u5C06\u5728\u4E0B\u6B21\u8BF7\u6C42\u65F6\u53D1\u9001")),I.createElement(S,{flexDirection:"column"},I.createElement(y,{dimColor:true},"\u8F93\u5165\u4F60\u7684\u6D88\u606F:"),I.createElement(S,{marginTop:1},I.createElement(y,{color:"green",bold:true},"\u276F "),t?I.createElement(y,null,a,I.createElement(y,{inverse:true},l),c):I.createElement(S,null,I.createElement(y,{inverse:true}," "),I.createElement(y,{dimColor:true},"\u8F93\u5165\u6D88\u606F...")))),I.createElement(S,{marginTop:1,justifyContent:"space-between"},I.createElement(y,{dimColor:true},"Enter: \u786E\u8BA4"),I.createElement(y,{dimColor:true},"ESC: \u53D6\u6D88")))};var Bs=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:String(s),F_=s=>{switch(s){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},By=({agentContextStats:s,onClose:e})=>{let{columns:t}=Co();et((r,o)=>{(o.escape||r==="q")&&e();},{isActive:true});let n=[...s].sort((r,o)=>r.agentId==="Main"?-1:o.agentId==="Main"?1:r.agentLabel.localeCompare(o.agentLabel));return I.createElement(S,{flexDirection:"column",width:"100%"},I.createElement(S,{justifyContent:"space-between"},I.createElement(y,{bold:true,color:"cyan"},"Agent Context Overview"),I.createElement(y,{dimColor:true},"ESC to close")),I.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),n.length===0?I.createElement(y,{dimColor:true},"No agent context stats available."):n.map(r=>{let o=r.contextWindow||0,i=r.tokensUsedForContext||0,a=o>0?i/o:0,l=Math.round(a*100),{icon:c,color:u}=F_(r.status),d=r.currentTask?r.currentTask.length>40?`${r.currentTask.slice(0,37)}...`:r.currentTask:"";return I.createElement(S,{key:r.agentId,justifyContent:"space-between",marginTop:1},I.createElement(S,null,I.createElement(y,{color:"magenta"},r.agentLabel),I.createElement(y,{dimColor:true}," "),I.createElement(y,{color:u},c),d&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," "),I.createElement(y,{dimColor:true},d))),I.createElement(S,null,I.createElement(y,{dimColor:true},"in "),I.createElement(y,{color:"cyan"},Bs(r.input)),I.createElement(y,{dimColor:true}," out "),I.createElement(y,{color:"green"},Bs(r.output)),(r.cacheCreationTokens||r.cacheReadTokens)&&I.createElement(I.Fragment,null,I.createElement(y,{dimColor:true}," cache-w "),I.createElement(y,{color:"magenta"},Bs(r.cacheCreationTokens||0)),I.createElement(y,{dimColor:true}," cache-r "),I.createElement(y,{color:"blue"},Bs(r.cacheReadTokens||0))),I.createElement(y,{dimColor:true}," \u2502 context "),I.createElement(y,{color:"yellow"},Bs(i)),I.createElement(y,{dimColor:true},"/"),I.createElement(y,{color:"yellow"},Bs(o)),I.createElement(y,{dimColor:true}," ("),I.createElement(y,{color:a>.8?"red":a>.5?"yellow":"green"},l,"%"),I.createElement(y,{dimColor:true},")")))}),I.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),I.createElement(y,{dimColor:true},"Tip: Press Q or ESC to return"))};Zd();Z();var K_=[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg"];function J_(s){if(!s)return false;let e=s.trim(),t=e.toLowerCase(),n=K_.some(o=>t.endsWith(o)),r=e.startsWith("/")||e.startsWith("./")||e.startsWith("~/")||e.includes("/")&&n;return n&&r}var Fy=({staticEntries:s=[],pendingEntries:e=[],isRunning:t,statusText:n="",tokenStats:r,streamingTokens:o=0,streamingStartTime:i=null,accumulatedRunTime:a=0,version:l=Cl,provider:c="OpenAI",model:u="gpt-4",workDir:d=process.cwd(),showHeader:m=true,thinkingEnabled:g=true,selectMenuOptions:h=null,textPromptOptions:f=null,contextMenuActive:v=false,agentContextScreenActive:b=false,compressionMode:C="sync",compactionThreshold:T=.85,agentContextStats:w=[],runMode:E="single",networkStats:N,cooperateStats:D,commandOutput:$=[],attachedImages:k=[],interruptInputActive:M=false,getCompletions:_,onStaticRendered:P,onSubmit:j,onInterrupt:z,onExit:A,onContextMenuToggle:O,onAgentContextScreenToggle:F,onClearCommandOutput:U,onAttachImage:K,onClearImages:de,onInterruptInputSubmit:W,onInterruptInputCancel:H,onShowInterruptInput:ne})=>{let[J,fe]=useState(""),[V,re]=useState([]),[ue,se]=useState(-1),[ae,ee]=useState(null),ve=useRef(false),L=useContext(Zr);useEffect(()=>{if(!L?.internal_eventEmitter||!K)return;let Y=me=>{oe("CLI_APP",`\u{1F4CE} Received image-paste event from vendor Ink: ${me.name}`),K(me);};return L.internal_eventEmitter.on("image-paste",Y),()=>{L.internal_eventEmitter.off("image-paste",Y);}},[L,K]),useEffect(()=>{f?.defaultValue&&fe(f.defaultValue);},[f?.defaultValue]),et((Y,me)=>{if(me.escape){if(b)return;ae?ee(null):$.length>0&&U&&U();}},{isActive:true});let q=e.filter(Y=>Y.type!=="thinking"&&Y.type!=="reasoning"),Q=Y=>{if(!Y)return false;let{content:me}=Y;return typeof me=="string"?me.trim().length>0:Array.isArray(me)?me.some(pe=>{if(!pe||typeof pe!="object"||!("type"in pe))return false;switch(pe.type){case "text":return typeof pe.text=="string"&&pe.text.trim().length>0;case "image_url":return true;case "tool_use":return true;case "tool_result":return pe.content!==null&&pe.content!==void 0&&String(pe.content).trim().length>0;case "thinking":return typeof pe.thinking=="string"&&pe.thinking.trim().length>0;case "redacted_thinking":return typeof pe.data=="string"&&pe.data.trim().length>0;default:return true}}):false},le=Y=>{if(Y.message)return Q(Y.message);let me=typeof Y.text=="string"&&Y.text.trim().length>0,pe=Y.type==="plan"&&!!Y.planSteps&&Y.planSteps.length>0,_e=(Y.type==="pipeline_node_start"||Y.type==="pipeline_node_complete"||Y.type==="pipeline_node_fail"||Y.type==="pipeline_node_retry")&&(Y.pipelineNode||Y.pipelineNodeRetry),Ot=(Y.type==="network_node_start"||Y.type==="network_node_complete"||Y.type==="network_node_fail")&&Y.networkNode,He=(Y.type==="ccb_review"||Y.type==="ccb_agent_review"||Y.type==="ccb_retry"||Y.type==="ccb_failed")&&!!(Y.ccbReview||Y.ccbAgentReview||Y.ccbRetry||Y.ccbFailed),Wt=Y.type==="pipeline_dag"&&!!Y.pipelineDAG;return !!(me||pe||_e||Ot||He||Wt)},Ee=useMemo(()=>q.filter(le),[q]),Pe=useMemo(()=>s.filter(le),[s]),G=m&&!ve.current,X=I.useCallback((Y,me)=>Y,[]),te=useMemo(()=>{let Y=[],me=Pe.length+Ee.length;return G&&Y.push(I.createElement(uy,{key:"header",version:l,provider:c,model:u,workDir:d})),Pe.forEach((pe,_e)=>{Y.push(I.createElement(qd,{key:`static-entry-${pe.id}`,entry:pe})),(_e<Pe.length-1||me>Pe.length)&&Y.push(I.createElement(y,{key:`static-spacer-${pe.id}`},""));}),Y},[G,Pe,Ee.length,l,c,u,d]);if(useEffect(()=>{!G&&s.length===0||(G&&(ve.current=true),P?.());},[G,s.length,P]),b)return I.createElement(By,{agentContextStats:w,onClose:()=>F?.()});let Ne=Y=>{if(f){if(!Y.trim()&&!f.allowEmpty)return;f.onSubmit(Y),fe("");return}let me=k.length>0,pe=Y.trim().length>0;(pe||me)&&(pe&&re([...V,Y]),se(-1),fe(""),j(Y,me?k:void 0));},Re=()=>{if(V.length===0)return;let Y=ue+1;Y<V.length&&(se(Y),fe(V[V.length-1-Y]));},De=()=>{if(ue<=0){se(-1),fe("");return}let Y=ue-1;se(Y),fe(V[V.length-1-Y]);},ke=Y=>{if(!_)return null;let me=_(Y);if(me.length===0)return null;if(me.length===1)return me[0];let pe=me.map(_e=>({label:_e,value:_e,description:void 0}));return ee({message:"Select completion:",choices:pe,initialIndex:0,onSelect:_e=>{fe(_e),ee(null);},onCancel:()=>{ee(null);}}),null};return I.createElement(S,{flexDirection:"column",width:"100%"},I.createElement(ua,{items:te},X),Ee.map((Y,me)=>I.createElement(S,{key:`pending-wrapper-${Y.id}`,flexDirection:"column"},I.createElement(qd,{entry:Y}),me<Ee.length-1&&I.createElement(y,null,""))),I.createElement(y,null,`
|
|
1684
|
+
`),I.createElement(S,{flexShrink:0,flexDirection:"column"},I.createElement(Ly,{inputValue:J,isRunning:t,statusText:n,tokenStats:r,streamingTokens:o,streamingStartTime:i,accumulatedRunTime:a,provider:c,model:u,menuActive:!!h||!!ae,promptActive:!!f,promptMessage:f?.message,promptHint:f?.hint,promptOnCancel:f?.onCancel,thinkingEnabled:g,contextMenuActive:v,compressionMode:C,compactionThreshold:T,agentContextStats:w,runMode:E,networkStats:N,cooperateStats:D,attachments:k,onInputChange:Y=>{if(K&&J_(Y)){K(Y.trim());return}fe(Y);},onSubmit:Ne,onInterrupt:z,onExit:A,onHistoryUp:Re,onHistoryDown:De,onTabComplete:ke,onContextMenuToggle:O,onAgentContextScreenToggle:F,onRemoveAttachment:de?Y=>{de();}:void 0,onPasteImage:K,onShowInterruptInput:ne}),h&&I.createElement(Yd,{message:h.message,choices:h.choices,initialIndex:h.initialIndex,hint:h.hint,onSelect:h.onSelect,onCancel:h.onCancel,onExit:A}),ae&&I.createElement(Yd,{message:ae.message,choices:ae.choices,initialIndex:ae.initialIndex,hint:ae.hint,onSelect:ae.onSelect,onCancel:ae.onCancel,onExit:A}),$.length>0&&I.createElement(S,{flexDirection:"column",paddingX:2,paddingY:1,borderStyle:"round",borderColor:"gray"},$.map((Y,me)=>I.createElement(y,{key:me},Y)))),M&&W&&H&&I.createElement(S,{flexDirection:"column",justifyContent:"center",alignItems:"center",marginTop:5},I.createElement($y,{onSubmit:W,onCancel:H})))};Z();var Tl=class s{appInstance=null;messages=[];staticEntries=[];nextEntryId=1;isRunning=false;statusText="";tokenStats={input:0,output:0,total:0,contextWindow:void 0,tokensUsedForContext:0,pressure:0};version="";provider="";model="";workDir="";showHeader=true;thinkingEnabled=true;callbacks;forceUpdate=null;selectMenuOptions=null;textPromptOptions=null;contextMenuActive=false;agentContextScreenActive=false;commandOutput=[];getCompletions;memoryLogTimer=null;attachedImages=[];pendingEntries=[];queuedMessages=[];nextQueuedMessageId=1;interruptInputActive=false;runMode="single";streamingTokens=0;streamingStartTime=null;accumulatedRunTime=0;runningStartTime=null;compressionMode="sync";compactionThreshold=.85;agentContextStats=new Map;networkStats=null;cooperateStats=null;static MAX_QUEUED_STATIC=50;constructor(e){this.callbacks=e;}setCompletionFunction(e){this.getCompletions=e;}start(){p.info("INK","Starting Ink runtime"),this.startMemorySampler();let e=()=>{let[,t]=useState(0);return useEffect(()=>(this.forceUpdate=()=>{let n=Date.now();p.debug("RUNTIME",`>>> forceUpdate called, staticEntries=${this.staticEntries.length}, pendingEntries=${this.pendingEntries.length}`),t(o=>o+1);let r=Date.now()-n;r>50&&p.warn("RUNTIME",`\u26A0\uFE0F forceUpdate slow: setCounter took ${r}ms`);},()=>{this.forceUpdate=null;}),[]),I.createElement(Fy,{staticEntries:this.staticEntries,pendingEntries:this.pendingEntries,isRunning:this.isRunning,statusText:this.statusText,tokenStats:this.tokenStats,streamingTokens:this.streamingTokens,streamingStartTime:this.streamingStartTime,accumulatedRunTime:this.accumulatedRunTime,compressionMode:this.compressionMode,compactionThreshold:this.compactionThreshold,agentContextStats:this.getAgentContextStats(),runMode:this.runMode,networkStats:this.networkStats||void 0,cooperateStats:this.cooperateStats||void 0,version:this.version,provider:this.provider,model:this.model,workDir:this.workDir,showHeader:this.showHeader,thinkingEnabled:this.thinkingEnabled,selectMenuOptions:this.selectMenuOptions,textPromptOptions:this.textPromptOptions,contextMenuActive:this.contextMenuActive,agentContextScreenActive:this.agentContextScreenActive,commandOutput:this.commandOutput,attachedImages:this.attachedImages,interruptInputActive:this.interruptInputActive,getCompletions:this.getCompletions,onStaticRendered:void 0,onSubmit:(n,r)=>{let o=r||this.attachedImages;this.attachedImages=[],this.callbacks.onSubmit(n,o);},onInterrupt:this.callbacks.onInterrupt,onExit:this.callbacks.onExit,onContextMenuToggle:()=>{this.contextMenuActive=!this.contextMenuActive,this.forceUpdate?.();},onAgentContextScreenToggle:()=>{this.agentContextScreenActive=!this.agentContextScreenActive,this.forceUpdate?.();},onClearCommandOutput:()=>{this.clearCommandOutput();},onAttachImage:n=>{this.attachImage(n);},onClearImages:()=>{this.clearAttachedImages();},onInterruptInputSubmit:n=>{this.handleInterruptInputSubmit(n);},onInterruptInputCancel:()=>{this.hideInterruptInput();},onShowInterruptInput:()=>{this.showInterruptInput();}})};this.appInstance=rs(I.createElement(e,null),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:false,patchConsole:false});try{process.stdout.isTTY&&!process.stdout.destroyed&&(process.stdout.write("\x1B[?2004h"),p.info("INK","Bracketed paste mode enabled for image paste detection"));}catch(t){p.warn("INK","Failed to enable bracketed paste mode",{error:t});}try{p.debug("TTY_STATE","\u{1F6E1}\uFE0F [INK] Re-registering SIGTSTP ignore handler after Ink starts"),process.removeAllListeners("SIGTSTP"),process.on("SIGTSTP","ignore"),p.debug("TTY_STATE","\u2705 [INK] SIGTSTP handler re-registered (Ctrl+Z ignored)"),process.env.CLI_DEBUG==="1"&&p.debug("INK","SIGTSTP handler registered (Ctrl+Z ignored)");}catch{p.debug("TTY_STATE","\u26A0\uFE0F [INK] SIGTSTP not supported on this platform"),process.env.CLI_DEBUG==="1"&&p.debug("INK","SIGTSTP not supported on this platform");}p.info("INK","Ink runtime started");}stop(){try{process.stdout.isTTY&&!process.stdout.destroyed&&(process.stdout.write("\x1B[?2004l"),p.debug("INK","Bracketed paste mode disabled"));}catch(e){p.debug("INK","Failed to disable bracketed paste mode (ignored)",{error:e});}this.appInstance&&(this.appInstance.unmount(),this.appInstance=null,p.info("INK","Ink runtime stopped")),this.stopMemorySampler();}addMessage(e){this.messages=[...this.messages.slice(-4),e],this.forceUpdate?.();}addEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};return this.staticEntries.length>=s.MAX_QUEUED_STATIC&&(p.warn("INK_RUNTIME",`Static queue reached limit (${this.staticEntries.length}). Forcing immediate render to prevent OOM.`),this.forceUpdate?.(),setImmediate(()=>{this.clearStaticEntries();})),this.staticEntries=[...this.staticEntries,t],p.debug("INK_RUNTIME",`Queued static entry ${t.id}. Pending static: ${this.staticEntries.length}`),this.forceUpdate?.(),t.id}updateEntry(e,t){let n=this.staticEntries.findIndex(o=>o.id===e);if(n>=0){this.staticEntries=this.staticEntries.map((o,i)=>i===n?{...o,...t}:o),this.forceUpdate?.();return}let r=this.pendingEntries.findIndex(o=>o.id===e);r>=0&&(this.pendingEntries=this.pendingEntries.map((o,i)=>i===r?{...o,...t}:o),this.forceUpdate?.());}getEntry(e){return this.staticEntries.find(t=>t.id===e)||this.pendingEntries.find(t=>t.id===e)}addPendingEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};if(this.pendingEntries.length>=10){p.warn("INK_RUNTIME",`Too many pending entries (${this.pendingEntries.length}). Auto-committing oldest.`);let r=this.pendingEntries[0];this.staticEntries=[...this.staticEntries,r],this.pendingEntries=this.pendingEntries.slice(1);}return this.pendingEntries=[...this.pendingEntries,t],p.debug("INK_RUNTIME",`Added pending entry ${t.id}. Pending: ${this.pendingEntries.length}`),this.forceUpdate?.(),t.id}updatePendingEntry(e,t){let n=this.pendingEntries.findIndex(r=>r.id===e);n>=0&&(this.pendingEntries=this.pendingEntries.map((r,o)=>o===n?{...r,...t}:r),this.forceUpdate?.());}updatePendingEntryByKey(e,t){let n=this.pendingEntries.findIndex(r=>r.entryKey===e);if(n>=0)this.pendingEntries=this.pendingEntries.map((r,o)=>o===n?{...r,...t,entryKey:e,timestamp:new Date}:r);else {let r={...t,entryKey:e,id:this.nextEntryId++,timestamp:new Date};this.pendingEntries=[...this.pendingEntries,r];}this.forceUpdate?.();}commitPendingEntryByKey(e){let t=this.pendingEntries.findIndex(n=>n.entryKey===e);if(t>=0){let n=this.pendingEntries[t];return this.pendingEntries=this.pendingEntries.filter((r,o)=>o!==t),this.staticEntries=[...this.staticEntries,{...n,isStreaming:false,isComplete:true}],p.debug("INK_RUNTIME",`Committed entry by key ${e}. Static: ${this.staticEntries.length}, Pending: ${this.pendingEntries.length}`),this.forceUpdate?.(),true}return false}commitPendingEntry(e){let t=this.pendingEntries.findIndex(n=>n.id===e);if(t>=0){let n=this.pendingEntries[t];this.pendingEntries=this.pendingEntries.filter((r,o)=>o!==t),this.staticEntries=[...this.staticEntries,n],p.debug("INK_RUNTIME",`Committed entry ${e}. Static: ${this.staticEntries.length}, Pending: ${this.pendingEntries.length}`),this.forceUpdate?.();}else p.warn("INK_RUNTIME",`Cannot commit entry ${e} - not found in pending entries`);}clearPendingEntries(){this.pendingEntries.length>0&&(this.pendingEntries=[],this.forceUpdate?.());}updateStreamingStats(e){this.streamingTokens=e,this.streamingStartTime||(this.streamingStartTime=Date.now()),this.forceUpdate?.();}resetStreamingStats(){this.streamingTokens=0,this.streamingStartTime=null;}getAccumulatedRunTime(){if(this.isRunning&&this.runningStartTime!==null){let e=Math.floor((Date.now()-this.runningStartTime)/1e3);return this.accumulatedRunTime+e}return this.accumulatedRunTime}resetAccumulatedRunTime(){this.accumulatedRunTime=0,this.runningStartTime=null,this.forceUpdate?.();}setCompressionMode(e){this.compressionMode!==e&&(this.compressionMode=e,this.forceUpdate?.());}setCompactionThreshold(e){this.compactionThreshold!==e&&(this.compactionThreshold=e,this.forceUpdate?.());}updateAgentContext(e,t){this.agentContextStats.set(e,t),this.forceUpdate?.();}clearAgentContext(e){this.agentContextStats.has(e)&&(this.agentContextStats.delete(e),this.forceUpdate?.());}clearAllAgentContexts(){this.agentContextStats.size>0&&(this.agentContextStats.clear(),this.forceUpdate?.());}getAgentContextStats(){return Array.from(this.agentContextStats.values()).sort((t,n)=>t.agentId==="supervisor"?-1:n.agentId==="supervisor"?1:t.agentId.localeCompare(n.agentId))}updateLastMessage(e){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1];if(typeof t.content=="string")t.content=e;else if(Array.isArray(t.content)){let n=t.content.find(r=>r.type==="text");n&&"text"in n&&(n.text=e);}this.forceUpdate?.();}getLastMessageText(){if(this.messages.length===0)return "";let e=this.messages[this.messages.length-1];if(typeof e.content=="string")return e.content;if(Array.isArray(e.content)){let t=e.content.find(n=>n.type==="text");if(t&&"text"in t)return t.text||""}return ""}setRunning(e){if(this.isRunning!==e){if(e)this.runningStartTime=Date.now();else if(this.runningStartTime!==null){let t=Math.floor((Date.now()-this.runningStartTime)/1e3);this.accumulatedRunTime+=t,this.runningStartTime=null;}this.isRunning=e,this.forceUpdate?.();}}setStatusText(e){this.statusText!==e&&(this.statusText=e,this.forceUpdate?.());}setTokenStats(e){p.info("DEBUG_CTX",`InkRuntime.setTokenStats: received contextWindow=${e.contextWindow}, current=${this.tokenStats.contextWindow}`);let t=e.contextWindow!==void 0?e.contextWindow:this.tokenStats.contextWindow;(this.tokenStats.input!==e.input||this.tokenStats.output!==e.output||this.tokenStats.total!==e.total||this.tokenStats.contextWindow!==t||this.tokenStats.tokensUsedForContext!==e.tokensUsedForContext||this.tokenStats.pressure!==e.pressure||this.tokenStats.toolTokens!==e.toolTokens||this.tokenStats.messageTokens!==e.messageTokens||this.tokenStats.systemTokens!==e.systemTokens||this.tokenStats.userTokens!==e.userTokens||this.tokenStats.assistantTokens!==e.assistantTokens||this.tokenStats.toolCallTokens!==e.toolCallTokens||this.tokenStats.toolResultTokens!==e.toolResultTokens||this.tokenStats.cacheCreationTokens!==e.cacheCreationTokens||this.tokenStats.cacheReadTokens!==e.cacheReadTokens)&&(this.tokenStats={...e,contextWindow:t,tokensUsedForContext:e.tokensUsedForContext??this.tokenStats.tokensUsedForContext,pressure:e.pressure??this.tokenStats.pressure},p.info("DEBUG_CTX",`InkRuntime.setTokenStats: after update contextWindow=${this.tokenStats.contextWindow}`),this.forceUpdate?.());}clearMessages(){p.warn("INK_RUNTIME",`clearMessages called! This will clear pending/static queues. Messages: ${this.messages.length}`),this.messages=[],this.staticEntries=[],this.pendingEntries=[],this.forceUpdate?.();}setCommandOutput(e){p.debug("INK_RUNTIME","Set command output",{lineCount:e.length}),this.commandOutput=e,this.forceUpdate?.();}clearCommandOutput(){p.debug("INK_RUNTIME","Clear command output"),this.commandOutput=[],this.forceUpdate?.();}attachImage(e){let t;if(typeof e=="string")if(e.startsWith("data:")){let r=e.match(/^data:([^;]+);base64,(.+)$/);if(r){let o=`image_${Date.now()}.png`;t={mediaType:r[1],data:r[2],name:o};}else {p.error("INK_RUNTIME","Invalid data URL format",{imageData:e});return}}else {let r=e.split("/").pop()||e;t={path:e,name:r};}else t=e;if(this.attachedImages.some(r=>r.path&&t.path&&r.path===t.path||r.data&&t.data&&r.data===t.data)){p.debug("INK_RUNTIME","Image already attached");return}this.attachedImages.push(t),p.info("INK_RUNTIME",`\u{1F4CE} Attached image #${this.attachedImages.length}: ${t.name||"unnamed"}`),this.forceUpdate?.();}clearAttachedImages(){this.attachedImages.length>0&&(p.debug("INK_RUNTIME",`Cleared ${this.attachedImages.length} attached images`),this.attachedImages=[],this.forceUpdate?.());}getAttachedImages(){return [...this.attachedImages]}showInterruptInput(){p.debug("INK_RUNTIME","Show interrupt input"),this.interruptInputActive=true,this.forceUpdate?.();}hideInterruptInput(){p.debug("INK_RUNTIME","Hide interrupt input"),this.interruptInputActive=false,this.forceUpdate?.();}handleInterruptInputSubmit(e){let t={id:this.nextQueuedMessageId++,text:e,timestamp:new Date};this.queuedMessages.push(t),p.info("INK_RUNTIME",`\u{1F4E8} Queued interrupt message #${t.id}: "${e.substring(0,50)}..."`),this.addEntry({type:"queued_message",text:"\u2728 \u63D2\u961F\u6D88\u606F (\u5C06\u5728\u4E0B\u6B21\u8BF7\u6C42\u65F6\u53D1\u9001)",details:e}),this.hideInterruptInput();}getAndClearQueuedMessages(){let e=[...this.queuedMessages];return this.queuedMessages=[],e.length>0&&p.info("INK_RUNTIME",`\u{1F4E4} Returning ${e.length} queued messages to main loop`),e}hasQueuedMessages(){return this.queuedMessages.length>0}addAgentSpawnEntry(e,t,n,r){return this.addEntry({type:"agent_spawn",agentId:e,agentIndex:t,agentStatus:"running",agentTask:n,agentModel:r,text:n})}addAgentProgressEntry(e,t,n,r){return this.addEntry({type:"agent_progress",agentId:e,agentIndex:t,agentStatus:"running",agentProgress:n,text:r})}addAgentCompleteEntry(e,t,n){return this.addEntry({type:"agent_complete",agentId:e,agentIndex:t,agentStatus:"completed",text:n})}addAgentErrorEntry(e,t,n){return this.addEntry({type:"agent_error",agentId:e,agentIndex:t,agentStatus:"error",agentError:n,text:n})}setVersion(e){this.version=e,this.forceUpdate?.();}setProvider(e){this.provider=e,this.forceUpdate?.();}setModel(e){this.model=e,this.forceUpdate?.();}setRunMode(e){this.runMode=e,e!=="network"&&(this.networkStats=null),this.forceUpdate?.();}updateNetworkStats(e){this.networkStats||(this.networkStats={teamSize:0,activeAgents:0,totalInputTokens:0,totalOutputTokens:0}),Object.assign(this.networkStats,e),this.forceUpdate?.();}clearNetworkStats(){this.networkStats=null,this.forceUpdate?.();}getNetworkStats(){return this.networkStats}updateCooperateStats(e){this.cooperateStats||(this.cooperateStats={models:[],totalInputTokens:0,totalOutputTokens:0}),Object.assign(this.cooperateStats,e),this.forceUpdate?.();}clearCooperateStats(){this.cooperateStats=null,this.forceUpdate?.();}getCooperateStats(){return this.cooperateStats}setWorkDir(e){this.workDir=e,this.forceUpdate?.();}setShowHeader(e){this.showHeader=e,this.forceUpdate?.();}setThinkingEnabled(e){this.thinkingEnabled!==e&&(this.thinkingEnabled=e,this.forceUpdate?.());}showSelectMenu(e){if(p.debug("INK_RUNTIME","Show select menu",{options:e}),process.stdin.isTTY&&!process.stdin.destroyed){let t=process.stdin.isPaused?.()||false;process.stdin.isRaw||false;if(t){process.env.CLI_DEBUG==="1"&&p.debug("INK_RUNTIME",`showSelectMenu: Resuming stdin (wasPaused=${t})`);try{process.stdin.resume(),p.info("INK_RUNTIME","\u2713 Stdin resumed for SelectMenu");}catch(r){p.error("INK_RUNTIME","Failed to resume stdin for SelectMenu",{error:r});}}}this.selectMenuOptions=e,this.forceUpdate?.();}hideSelectMenu(){p.debug("INK_RUNTIME","Hide select menu"),this.selectMenuOptions=null,this.forceUpdate?.(),process.nextTick(()=>{this.forceUpdate?.();});}isSelectMenuActive(){return this.selectMenuOptions!==null}updateSelectMenuIndex(e){if(!this.selectMenuOptions)return;let t=Math.max(0,this.selectMenuOptions.choices.length-1),n=Math.max(0,Math.min(e,t));this.selectMenuOptions={...this.selectMenuOptions,initialIndex:n},this.forceUpdate?.();}showTextPrompt(e){if(p.debug("INK_RUNTIME","Show text prompt",{options:e}),process.stdin.isTTY&&!process.stdin.destroyed){let t=process.stdin.isPaused?.()||false;if(t){process.env.CLI_DEBUG==="1"&&p.debug("INK_RUNTIME",`showTextPrompt: Resuming stdin (wasPaused=${t})`);try{process.stdin.resume(),p.info("INK_RUNTIME","\u2713 Stdin resumed for TextPrompt");}catch(n){p.error("INK_RUNTIME","Failed to resume stdin for TextPrompt",{error:n});}}}this.textPromptOptions=e,this.forceUpdate?.();}hideTextPrompt(){p.debug("INK_RUNTIME","Hide text prompt"),this.textPromptOptions=null,this.forceUpdate?.();}showContextMenu(){p.debug("INK_RUNTIME","Show context menu"),this.contextMenuActive=true,this.forceUpdate?.();}hideContextMenu(){p.debug("INK_RUNTIME","Hide context menu"),this.contextMenuActive=false,this.forceUpdate?.();}getContextMenuActive(){return this.contextMenuActive}clearStaticEntries(){if(this.staticEntries.length===0)return;let e=this.staticEntries.length;p.debug("INK_RUNTIME",`Clearing ${e} static entries from memory`),this.staticEntries=[],global.gc&&e>10&&(p.debug("INK_RUNTIME","Triggering manual GC after clearing entries"),setImmediate(()=>{global.gc&&global.gc();}));}startMemorySampler(){this.memoryLogTimer||process.env.INK_MEM!=="1"||(this.memoryLogTimer=setInterval(()=>{let e=process.memoryUsage(),t=n=>Math.round(n/1024/1024*10)/10;p.info("INK_MEM","usage",{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),heapTotalMB:t(e.heapTotal),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers??0),pendingEntries:this.pendingEntries.length,queuedStatic:this.staticEntries.length,isRunning:this.isRunning});},1e4));}stopMemorySampler(){this.memoryLogTimer&&(clearInterval(this.memoryLogTimer),this.memoryLogTimer=null);}};Z();var wl=class{runtime;config;callbacks;currentThinkingText="";lastMessageRole=null;lastEntryId=null;tokenStats={inputTokens:0,outputTokens:0,totalTokens:0};memory;streamingTextPendingId=null;streamingReasoningPendingId=null;streamingTextBuffer="";streamingReasoningBuffer="";streamingReasoningType="thinking";streamingToolChars=0;toolLogIdByToolId=new Map;toolLogDetailsByToolId=new Map;toolLogNameByToolId=new Map;toolLogOutputByToolId=new Map;toolLogSourceLabelByToolId=new Map;streamingSourceLabel=null;streamingSourceType=null;agentBuffers=new Map;activeAgentId=null;constructor(e){this.config=e,this.memory=e.memory,this.runtime=new Tl({onSubmit:(t,n)=>{this.callbacks?.onSubmit&&this.callbacks.onSubmit(t,n);},onInterrupt:()=>{this.callbacks?.onInterrupt&&this.callbacks.onInterrupt();},onExit:()=>{this.callbacks?.onExit&&this.callbacks.onExit();}});}start(e){this.callbacks=e,this.runtime.setVersion(this.config.version),this.runtime.setProvider(this.config.provider),this.runtime.setModel(this.config.model),this.runtime.setWorkDir(this.config.workDir),this.config.getCompletions&&this.runtime.setCompletionFunction(this.config.getCompletions),this.runtime.start(),p.info("INK_ADAPTER","Ink UI started");}stop(){this.runtime.stop(),this.callbacks=void 0,p.info("INK_ADAPTER","Ink UI stopped");}addUserMessage(e,t){let n=[{type:"text",text:e}];if(t&&t.length>0)for(let o of t)n.push({type:"image_url",image_url:{url:`file://${o.path}`}});let r={role:"user",content:n};this.lastEntryId=this.runtime.addEntry({type:"user",message:r}),this.lastMessageRole="user";}addAssistantMessage(e=""){if(e===""){this.lastMessageRole="assistant";return}let t={role:"assistant",content:[{type:"text",text:e}]};this.lastEntryId=this.runtime.addEntry({type:"assistant",message:t,isStreaming:false}),this.lastMessageRole="assistant";}addSupervisorMessage(e){let t={role:"user",content:[{type:"text",text:e}]};this.lastEntryId=this.runtime.addEntry({type:"supervisor",message:t}),this.lastMessageRole="user";}startSupervisorStreaming(){this.startAgentStreaming("Supervisor"),this.streamingSourceLabel="Supervisor",this.streamingSourceType="supervisor";}startExecutorStreaming(e){let t=e||"Executor";this.startAgentStreaming(t);}getStreamingSourceType(){return this.streamingSourceType}startAgentStreaming(e){this.agentBuffers.has(e)||this.agentBuffers.set(e,""),this.activeAgentId=e,this.lastMessageRole="assistant",p.debug("INK_ADAPTER",`Started agent streaming for ${e}`);}startWorkerStreaming(e){this.startAgentStreaming(e);}addWorkerTextDelta(e,t){this.streamText(t,e);}completeWorkerStreaming(e){this.completeTextStreaming(e);}addWorkerInfo(e,t,n,r="info"){let i=`${`[${e}]`} ${t}`,a=r==="error"?"warning":r;this.addInfo(i,n,a);}streamText(e,t){let n=Date.now(),r=t||this.activeAgentId||"default";p.debug("INK_ADAPTER",`streamText: ${e.length} chars to ${r}`,{snippet:e.substring(0,30),bufferExists:this.agentBuffers.has(r)});let o=Date.now()-n;o>10&&p.warn("INK_ADAPTER",`\u26A0\uFE0F streamText slow: ${o}ms for ${e.length} chars`);let i=this.agentBuffers.get(r)||"";this.agentBuffers.set(r,i+e);}addTextDelta(e,t){p.debug("INK_ADAPTER",`addTextDelta called: ${e.length} chars, agentId=${t||"default"}`,{delta:e.substring(0,50)}),this.streamText(e,t);}addAgentTextDelta(e,t,n){p.debug("INK_ADAPTER",`addAgentTextDelta: ${e.length} chars, agentId=${t}`,{delta:e.substring(0,50)}),this.agentBuffers.has(t)||this.agentBuffers.set(t,"");let r=this.agentBuffers.get(t)||"";this.agentBuffers.set(t,r+e);let i={role:"assistant",content:[{type:"text",text:this.agentBuffers.get(t)||""}]};this.runtime.updatePendingEntryByKey(t,{type:"assistant",message:i,isStreaming:true,isComplete:false,sourceLabel:n||t});}bufferAgentTextOnly(e,t){this.agentBuffers.has(t)||this.agentBuffers.set(t,"");let n=this.agentBuffers.get(t)||"";this.agentBuffers.set(t,n+e);}flushAgentBuffer(e){let t=this.agentBuffers.get(e)||"";return this.agentBuffers.delete(e),t}commitPendingEntryByKey(e){return this.agentBuffers.has(e)&&this.agentBuffers.delete(e),this.runtime.commitPendingEntryByKey(e)}addToolCall(e,t){let n={role:"assistant",content:[{type:"tool_use",id:`tool_${Math.floor(Date.now())}`,name:e,input:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_call";}addToolCallEntry(e,t,n){p.debug("INK_ADAPTER","Add tool call entry",{toolName:e,sourceLabel:n?.sourceLabel});let o={read_file:"readfile",Read:"readfile",search:"search",Grep:"search",grep:"search",glob:"search_files",Glob:"search_files",search_files:"search_files",smart_tree:"show_tree",tree:"show_tree",bash:"command_running",Bash:"command_running",shell:"command_running",execute_shell:"command_running",edit:"file_update",Edit:"file_update",write:"file_update",Write:"file_update",web_search:"web_search",WebSearch:"web_search",web_fetch:"web_fetch",WebFetch:"web_fetch",browser:"browser_debug",task:"task",Task:"task"}[e]||"tool_call",i=["bash","Bash","shell","execute_shell"].includes(e),a,l;i&&t.command?(l=`$ ${t.command}`,a="\u23F3 \u6B63\u5728\u6267\u884C\u4E2D..."):(l=e,a=JSON.stringify(t,null,2)),this.runtime.addEntry({type:o,text:l,details:a,isStreaming:i,sourceLabel:n?.sourceLabel});}addToolResult(e,t=false){let n={role:"user",content:[{type:"tool_result",tool_use_id:`tool_${Math.floor(Date.now())}`,content:e,is_error:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_result";}addEntry(e){return p.debug("INK_ADAPTER",`AddEntry: ${e.type}`,{text:e.text}),this.runtime.addEntry(e)}addInfo(e,t,n="info"){p.info("INK_ADAPTER",`Info: ${e}`,t?{details:t}:void 0);let r=n==="warning"||e.includes("\u26A0")||e.includes("\u23F3")||e.includes("\u23F1\uFE0F")||e.includes("\u{1F504}");this.runtime.addEntry({type:r?"warning":"info",text:e,details:t});}addError(e,t){let n=typeof t=="string"?t:t?.details,r=typeof t=="object"?t?.sourceLabel:void 0;p.error("INK_ADAPTER",e,n?{details:n}:void 0),this.runtime.addEntry({type:"error",text:e,details:n,sourceLabel:r});}addWarning(e,t,n){p.warn("INK_ADAPTER",e,t?{details:t}:void 0),this.runtime.addEntry({type:"warning",text:e,details:t,sourceLabel:n?.sourceLabel});}addCompacting(e,t){p.info("INK_ADAPTER",`Compacting: ${e}`,t?{details:t}:void 0),this.runtime.addEntry({type:"compacting",text:e,details:t});}updateStatus(e,t){if(t==="tool_call"&&e.includes("Streaming:")){let n=e.match(/\((\d+) chars\)/);if(n){let r=parseInt(n[1],10);this.streamingToolChars=r,this.runtime.updateStreamingStats(r);}}else t!=="tool_call"&&(this.streamingToolChars=0);t==="compacting"||t==="thinking"||t==="tool_call"?this.runtime.setRunning(true):(t==="complete"||t==="error")&&this.runtime.setRunning(false),this.runtime.setStatusText(e);}setRunning(e){this.runtime.setRunning(e);}startSessionTimer(){}getAccumulatedRunTime(){return this.runtime.getAccumulatedRunTime()}resetAccumulatedRunTime(){this.runtime.resetAccumulatedRunTime();}setCompressionMode(e){this.runtime.setCompressionMode(e);}setCompactionThreshold(e){this.runtime.setCompactionThreshold(e/100);}updateTokenStats(e,t){this.tokenStats.inputTokens=e,this.tokenStats.outputTokens=t,this.tokenStats.totalTokens=e+t,this.runtime.setTokenStats({input:e,output:t,total:e+t});}updateAgentContext(e,t){this.runtime.updateAgentContext(e,t);}clearAgentContext(e){this.runtime.clearAgentContext(e);}clearAllAgentContexts(){this.runtime.clearAllAgentContexts();}getTokenStats(){return {...this.tokenStats}}setTokenStats(e,t,n){p.info("DEBUG_CTX",`InkUIAdapter.setTokenStats: input=${e}, output=${t}, extras.contextWindow=${n?.contextWindow}`),this.tokenStats={inputTokens:e,outputTokens:t,totalTokens:e+t,...n};let r=n?.anthropicCacheCreationTokens||n?.openaiCachedTokens||n?.cacheCreationTokens,o=n?.anthropicCacheReadTokens||n?.cacheReadTokens,i=n?.contextWindow||0,a=n?.tokensUsedForContext||e+t+(o||0),l=i>0?a/i:0;p.info("DEBUG_CTX",`InkUIAdapter.setTokenStats: passing to runtime contextWindow=${n?.contextWindow}, calculated contextWindow=${i}`),this.runtime.setTokenStats({input:e,output:t,total:e+t,contextWindow:n?.contextWindow,tokensUsedForContext:n?.tokensUsedForContext,pressure:l,systemTokens:n?.systemTokens,userTokens:n?.userTokens,assistantTokens:n?.assistantTokens,toolCallTokens:n?.toolCallTokens,toolResultTokens:n?.toolResultTokens,toolTokens:n?.toolTokens,messageTokens:n?.messageTokens,cacheCreationTokens:r,cacheReadTokens:o});}startThinking(){this.streamingReasoningBuffer="",this.streamingReasoningType="thinking";}streamThinking(e,t="thinking"){this.streamingReasoningBuffer+=e,this.streamingReasoningPendingId?this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{text:this.streamingReasoningBuffer}):(this.streamingReasoningType=t,this.streamingReasoningPendingId=this.runtime.addPendingEntry({type:t,text:this.streamingReasoningBuffer,isStreaming:true}));}endThinking(){if(!this.streamingReasoningPendingId){this.updateStatus("","info");return}try{this.streamingReasoningBuffer&&this.streamingReasoningBuffer.trim().length>0?(this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{isStreaming:!1,isComplete:!0}),this.runtime.commitPendingEntry(this.streamingReasoningPendingId),p.debug("INK_ADAPTER",`Committed reasoning entry (${this.streamingReasoningBuffer.length} chars)`)):p.debug("INK_ADAPTER","Discarding empty reasoning entry (no content)");}catch(e){p.warn("INK_ADAPTER","Failed to commit reasoning entry",{error:e});}finally{this.streamingReasoningPendingId=null,this.streamingReasoningBuffer="",this.runtime.resetStreamingStats(),this.updateStatus("","info");}}startTaskTimer(){this.runtime.setRunning(true);}stopTaskTimer(){this.runtime.setRunning(false);}setStreamingTokens(e){this.runtime.updateStreamingStats(e);}clear(){this.runtime.clearMessages(),this.lastMessageRole=null;}resetStreamingState(){this.agentBuffers.clear(),this.activeAgentId=null,this.streamingTextBuffer="",this.streamingTextPendingId=null,this.streamingReasoningBuffer="",this.streamingReasoningPendingId=null,this.currentThinkingText="",this.streamingToolChars=0,this.runtime.clearPendingEntries(),this.runtime.resetStreamingStats(),this.runtime.setStatusText(""),p.debug("INK_ADAPTER","Reset streaming state (cleared all pending entries and buffers)");}finalizeStreamingState(){let e=Array.from(this.agentBuffers.keys());if(e.length>0)for(let t of e)this.completeTextStreaming(t);else this.completeTextStreaming();this.completeReasoningStreaming();}startReasoningStreaming(){this.startThinking();}streamReasoningText(e){this.streamThinking(e);}addReasoningDelta(e){this.streamThinking(e,"reasoning");}completeReasoningStreaming(){this.endThinking();}addThinking(e){}completeTextStreaming(e){let t=e||this.activeAgentId||"default",n=this.agentBuffers.get(t)||"";if(!(n&&n.trim().length>0)){p.debug("INK_ADAPTER",`Complete text streaming (${t}) - no text to commit`),this.agentBuffers.delete(t),this.runtime.commitPendingEntryByKey(t),(t==="default"||t===this.activeAgentId)&&(this.streamingTextPendingId=null,this.streamingSourceLabel=null,this.streamingSourceType=null,this.runtime.resetStreamingStats());return}try{if(this.runtime.commitPendingEntryByKey(t))p.debug("INK_ADAPTER",`Complete text streaming (${t}) - committed pending entry ${n.length} chars`);else {let i={role:"assistant",content:[{type:"text",text:n}]};this.runtime.addEntry({type:"assistant",message:i,isStreaming:!1,isComplete:!0,sourceLabel:t==="default"?void 0:t}),p.debug("INK_ADAPTER",`Complete text streaming (${t}) - created static entry from buffer ${n.length} chars`);}}catch(o){p.warn("INK_ADAPTER","Failed to commit text entry",{error:o});}finally{this.agentBuffers.delete(t),(t==="default"||t===this.activeAgentId)&&(this.streamingTextPendingId=null,this.streamingSourceLabel=null,this.streamingSourceType=null,this.lastMessageRole="assistant",this.runtime.resetStreamingStats()),this.activeAgentId===t&&(this.activeAgentId=null);}}printCommandOutput(e){p.debug("INK_ADAPTER",`Command output: ${e}`);}setCommandOutputLines(e){p.debug("INK_ADAPTER",`Set command output lines: ${e.length}`),this.runtime.setCommandOutput(e);}clearCommandOutputLines(){p.debug("INK_ADAPTER","Clear command output lines"),this.runtime.clearCommandOutput();}startToolCallWithId(e,t,n,r){p.debug("INK_ADAPTER",`Start tool call: ${t}`,{toolId:e,args:n});let o=this.buildToolCallDetails(n,r),i=r?.sourceLabel,c={readfile:"readfile",Read:"readfile",read_file:"readfile",search:"search",Grep:"search",grep:"search",search_files:"search_files",Glob:"search_files",glob:"search_files",find_files:"search_files",show_tree:"show_tree",smart_tree:"show_tree",list_directory:"show_tree",ls:"show_tree",file_update:"file_update",Edit:"file_update",edit_file:"file_update",Write:"file_update",write_file:"file_update",command_exec:"command_exec",Bash:"command_exec",bash:"command_exec",shell:"command_exec",execute_command:"command_exec",code_exec:"code_exec",web_search:"web_search",WebSearch:"web_search",web_fetch:"web_fetch",WebFetch:"web_fetch",browser_debug:"browser_debug",TodoWrite:"todo",TodoRead:"todo",Task:"task",NotebookEdit:"notebook",NotebookRead:"notebook",AskUserQuestion:"ask_user"}[t]||"tool_call",u=this.runtime.addEntry({type:c,text:t,details:o,isStreaming:true,sourceLabel:i});this.toolLogIdByToolId.set(e,u),this.toolLogDetailsByToolId.set(e,o||""),this.toolLogNameByToolId.set(e,t),i&&this.toolLogSourceLabelByToolId.set(e,i);}updateToolCallOutput(e,t,n){p.debug("INK_ADAPTER",`Update tool output: ${e}`,{output:t});let r=this.toolLogIdByToolId.get(e);if(!r)return;let o=this.toolLogDetailsByToolId.get(e)||"",i=this.formatToolOutput(t,n?.truncated);i&&this.toolLogOutputByToolId.set(e,i);let a=this.mergeToolDetails(o,i);this.runtime.updateEntry(r,{details:a,isStreaming:true});}completeToolCall(e,t){p.debug("INK_ADAPTER",`Complete tool call: ${e}`);let n=this.toolLogIdByToolId.get(e);if(!n){t?.result&&this.addToolResult(t.result,t.isError||false);return}let r=this.toolLogNameByToolId.get(e)||"",o=this.toolLogDetailsByToolId.get(e)||"",i=this.toolLogOutputByToolId.get(e)||"",a=this.toolLogSourceLabelByToolId.get(e),l=t?.summary||t?.error||"",c=[];o&&c.push(o),l&&c.push(l),!l&&i&&c.push(i),typeof t?.duration=="number"&&c.push(`duration: ${this.formatDuration(t.duration)}`),typeof t?.resultLength=="number"&&c.push(`result: ${t.resultLength}B`);let u=c.length>0?c.join(`
|
|
1685
1685
|
`):void 0;this.runtime.updateEntry(n,{type:t?.success?"tool_result":"tool_error",text:r||void 0,details:u,isStreaming:false,isComplete:true,sourceLabel:a}),this.toolLogIdByToolId.delete(e),this.toolLogDetailsByToolId.delete(e),this.toolLogNameByToolId.delete(e),this.toolLogOutputByToolId.delete(e),this.toolLogSourceLabelByToolId.delete(e);}updateTaskTokens(e,t=false){p.debug("INK_ADAPTER",`Update task tokens: ${e}`,{isActual:t}),!t&&this.runtime.updateStreamingStats(e);}addToolError(e,t){p.error("INK_ADAPTER",`Tool error: ${e}`,{error:t}),this.addToolResult(t,true);}printCommandOutputLines(e){e.forEach(t=>this.printCommandOutput(t));}resetTokenStats(){this.tokenStats={inputTokens:0,outputTokens:0,totalTokens:0},this.runtime.setTokenStats({input:0,output:0,total:0});}pause(){p.debug("INK_ADAPTER","Pause UI");}resume(){p.debug("INK_ADAPTER","Resume UI");}refreshUI(){p.debug("INK_ADAPTER","Refresh UI");}updateProvider(e,t){this.config.provider=e,this.config.model=t,this.runtime.setProvider(e),this.runtime.setModel(t);}updateWorkDir(e){this.config.workDir=e,this.runtime.setWorkDir(e);}setThinkingEnabled(e){this.runtime.setThinkingEnabled(e);}setRunMode(e){this.runtime.setRunMode(e);}updateNetworkStats(e){this.runtime.updateNetworkStats(e);}clearNetworkStats(){this.runtime.clearNetworkStats();}updateCooperateStats(e){this.runtime.updateCooperateStats(e);}clearCooperateStats(){this.runtime.clearCooperateStats();}showContextMenu(){return new Promise(e=>{this.runtime.showContextMenu();let t=setInterval(()=>{this.runtime.getContextMenuActive()||(clearInterval(t),e());},100);})}async promptText(e){return new Promise(t=>{this.runtime.showTextPrompt({message:e.message,defaultValue:e.defaultValue??e.initial,hint:e.hint,allowEmpty:e.allowEmpty??false,onSubmit:n=>{this.runtime.hideTextPrompt(),t(n);},onCancel:()=>{this.runtime.hideTextPrompt(),t(null);}});})}async promptSelect(e){return new Promise(t=>{this.runtime.hideSelectMenu();let n=e.choices.map(o=>({label:o.title,value:o.value,description:o.description})),r=e.initial||0;if(e.initialValue){let o=e.choices.findIndex(i=>i.value===e.initialValue);o>=0&&(r=o);}setTimeout(()=>{this.runtime.showSelectMenu({message:e.message,choices:n,initialIndex:r,hint:e.hint,onSelect:o=>{this.runtime.hideSelectMenu(),setTimeout(()=>t(o),100);},onCancel:()=>{this.runtime.hideSelectMenu(),setTimeout(()=>t(null),100);}});},100);})}handleSelectBack(){return p.debug("INK_ADAPTER","Handle select back"),this.runtime.isSelectMenuActive()?(this.runtime.hideSelectMenu(),true):false}addWebSearchResult(e){if(e.status==="searching"){p.debug("INK_ADAPTER","Skip web search start (waiting for completion)");return}p.debug("INK_ADAPTER","Add web search result",{options:e});let t=e.query||"query",n=e.results?`Found ${e.results.length} results`:void 0;this.runtime.addEntry({type:"web_search",text:t,details:n,sourceLabel:e.sourceLabel});}addWebFetchResult(e){if(e.status==="fetching"){p.debug("INK_ADAPTER","Skip web fetch start (waiting for completion)");return}p.debug("INK_ADAPTER","Add web fetch result",{options:e});let t=e.url||"URL",n=e.contentLength?`${(e.contentLength/1024).toFixed(1)}KB`:e.contentPreview?`${e.contentPreview.length} chars`:void 0;this.runtime.addEntry({type:"web_fetch",text:t,details:n,sourceLabel:e.sourceLabel});}addReadFileResult(e){if(e.status==="reading"){p.debug("INK_ADAPTER","Skip read file start (waiting for completion)");return}p.debug("INK_ADAPTER","Add read file result",{options:e});let t=e.filePath||"file",n=[];e.totalLines&&n.push(`${e.totalLines} lines`),e.fileSize&&n.push(e.fileSize);let r=n.length>0?n.join(", "):void 0;this.runtime.addEntry({type:"readfile",text:t,details:r,sourceLabel:e.sourceLabel});}addSearchResult(e){if(e.status==="searching"){p.debug("INK_ADAPTER","Skip search start (waiting for completion)");return}p.debug("INK_ADAPTER","Add search result",{options:e});let t=[];if(e.pattern&&t.push(`pattern="${e.pattern}"`),e.filePath){let i=e.filePath==="."?".":e.filePath;t.push(`path="${i}"`);}e.mode&&t.push(`mode="${e.mode}"`),e.strategy&&t.push(`engine="${e.strategy}"`),e.status==="completed"?e.matchCount!==void 0&&t.push(`matches=${e.matchCount}`):e.status==="error"&&t.push("\u274C ERROR");let n=t.join(", "),r=[];if(e.command){let i=this.simplifyRipgrepCommand(e.command);r.push(`$ ${i}`),r.push("");}e.status==="error"&&e.error?r.push(this.parseErrorMessage(e.error)):e.details&&r.push(e.details);let o=r.length>0?r.join(`
|
|
1686
1686
|
`):void 0;this.runtime.addEntry({type:"search",text:n,details:o,sourceLabel:e.sourceLabel});}addSearchFilesResult(e){if(e.status==="searching"){p.debug("INK_ADAPTER","Skip search files start (waiting for completion)");return}p.debug("INK_ADAPTER","Add search files result",{options:e});let t=[];e.pattern&&t.push(`pattern="${e.pattern}"`),e.path&&t.push(`path="${e.path}"`),e.fileCount!==void 0&&t.push(`files=${e.fileCount}`);let n=t.length>0?t.join(", "):"Glob";this.runtime.addEntry({type:"search_files",text:n,sourceLabel:e.sourceLabel});}addShowTreeResult(e){if(e.status==="loading"){p.debug("INK_ADAPTER","Skip show tree start (waiting for completion)");return}p.debug("INK_ADAPTER","Add show tree result",{options:e});let n=[`path="${e.path||"."}"`];if(e.mode&&n.push(`mode="${e.mode}"`),e.maxDepth!==void 0&&e.maxDepth!==null&&n.push(`depth=${e.maxDepth}`),e.status==="completed"&&e.totalChars){let a=(e.totalChars/1024).toFixed(1);n.push(`${a}KB`);}else e.status==="error"&&n.push("\u274C ERROR");let r=n.join(", "),o=this.formatSmartTreeDetails(e.content),i;e.status==="error"&&e.error?i=`Error: ${e.error}`:o?i=o:e.content&&(i=e.content.length>500?e.content.slice(0,500)+"...":e.content),this.runtime.addEntry({type:"show_tree",text:r,details:i,sourceLabel:e.sourceLabel});}addCommandExecResult(e){if(e.status==="running"){p.debug("INK_ADAPTER","Add command exec running",{command:e.command});let r=`$ ${e.command||"command"}`;this.runtime.addEntry({type:"command_running",text:r,details:"\u23F3 \u6B63\u5728\u6267\u884C\u4E2D...",isStreaming:true,sourceLabel:e.sourceLabel});return}p.debug("INK_ADAPTER","Add command exec result",{options:e});let t=`$ ${e.command||"command"}`,n=e.output?.slice(0,500);this.runtime.addEntry({type:"command_exec",text:t,details:n,sourceLabel:e.sourceLabel});}addCodeExecResult(e){if(e.status==="running"){p.debug("INK_ADAPTER","Skip code exec start (waiting for completion)");return}p.debug("INK_ADAPTER","Add code exec result",{options:e});let t=`Code: ${e.toolName||"execute"}`,n=e.output?.slice(0,500);this.runtime.addEntry({type:"code_exec",text:t,details:n,sourceLabel:e.sourceLabel});}addBrowserDebugResult(e){if(e.status==="detecting"){p.debug("INK_ADAPTER","Skip browser debug start (waiting for completion)");return}p.debug("INK_ADAPTER","Add browser debug result",{data:e});let t=e.url||"unknown",n=[];e.summary&&n.push(e.summary),e.loadTime&&n.push(`Load: ${e.loadTime}ms`),e.consoleLogs&&n.push(`Logs: ${e.consoleLogs}`),e.errors?.length&&n.push(`Errors: ${e.errors.length}`);let r=n.length>0?n.join(", "):void 0;this.runtime.addEntry({type:"browser_debug",text:t,details:r,sourceLabel:e.sourceLabel});}showPlanUpdate(e,t,n){this.runtime.addEntry({type:"plan",planExplanation:e,planSteps:t,sourceLabel:n});}formatSmartTreeDetails(e){if(!e)return;let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return;let n;try{n=JSON.parse(t);}catch{return}if(!n||typeof n!="object"||Array.isArray(n)||!["path","project_types","root_dirs","modules","config_files","tip","error"].some(m=>Object.prototype.hasOwnProperty.call(n,m)))return;if(typeof n.error=="string"&&n.error.trim())return `error: ${n.error.trim()}`;let o=[],i=typeof n.path=="string"?n.path.trim():"";i&&o.push(`\u{1F4C1} Path: ${i}`);let a=this.formatSmartTreeList(n.project_types,6);a!==void 0&&o.push(`\u{1F4E6} Project Type: ${a}`);let l=this.formatSmartTreeList(n.root_dirs,12);l!==void 0&&o.push(`\u{1F4C2} Root Directories: ${l}`);let c=this.formatSmartTreeList(n.modules,12);c!==void 0&&o.push(`\u{1F527} Modules: ${c}`);let u=this.formatSmartTreeList(n.config_files,8);u!==void 0&&o.push(`\u2699\uFE0F Config Files: ${u}`);let d=typeof n.tip=="string"?n.tip.trim():"";if(d&&o.push(`\u{1F4A1} Tip: ${d}`),o.length!==0)return o.join(`
|
|
1687
1687
|
`)}formatSmartTreeList(e,t){if(!Array.isArray(e))return;let n=e.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>a.length>0);if(n.length===0)return "(none)";let r=n.slice(0,t),o=n.length-r.length,i=o>0?` ...(+${o} more)`:"";return `${r.join(", ")}${i}`}addWriteFileCall(e,t,n){p.debug("INK_ADAPTER","Add write file call",{filePath:e,sourceLabel:n});let r=t.split(`
|
|
@@ -1941,7 +1941,7 @@ Tool results are returned via tool_result messages.`}supportsExtendedThinking(e)
|
|
|
1941
1941
|
`;return l+d+c}function Xy(s,e=2e3){let t=s&&typeof s.toJSON=="function"?s.toJSON():s,n="";try{n=JSON.stringify(t??{},null,2);}catch{n=String(t??"");}return n?n.length>e?`${n.slice(0,e)}
|
|
1942
1942
|
...[truncated ${n.length-e} chars]`:n:"No headers"}var lp="You are Claude Code, Anthropic's official CLI for Claude.",MI=["claude-code-20250219","interleaved-thinking-2025-05-14"],Rl="2023-06-01",Dl=64,PI=1024;var Qy=18e4,Zy=6e4,eb={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"},cp={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"},Hs=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 n=typeof e.userId=="string"?e.userId.trim():"";this.claudeCodeUserId=n?this.sanitizeUserId(n):this.generateSafeUserId(),this.betaFeatures=e.betaFeatures||MI,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?lp:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=CI.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 r=os("anthropic",this.baseUrl);this.retryConfig=ar(void 0,{...r,...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 n=e.response?.data;if(typeof n=="string")t=n.toLowerCase();else if(n&&typeof n=="object"){let r={error:n.error,message:n.message,type:n.type,code:n.code};t=JSON.stringify(r).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 n={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},r=this.retryConfig.requestMaxRetries,o=null,i=n.disableCaching||false;for(let a=0;a<=r;a++){let l={...n,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);a===0&&this.logRequest(t.model||this.defaultModel,c);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",m=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(m.status!==200){let f="";for await(let T of m.data)f+=T.toString();let v=`${this.baseUrl}${d}`,b=Fn(v,this.buildHeaders(),c,!1);p.error("CURL","=== [chat] API Error - Full Request CURL ==="),p.error("CURL",b),p.error("CURL",`=== Error Headers: ${Xy(m.headers)} ===`),p.error("CURL",`=== Error Response: ${f.substring(0,1e3)} ===`);let C=new Error(`Anthropic API error: ${m.status}`);C.response={status:m.status,headers:m.headers,data:f};try{let T=JSON.parse(f);C.response.data=T,T.error?.message?C.message=`Anthropic API error: ${m.status} - ${T.error.message}`:T.message&&(C.message=`Anthropic API error: ${m.status} - ${T.message}`),this.debugLog("API Error Details",T);}catch{this.debugLog("API Error (non-JSON)",{status:m.status,dataLength:f.length});}throw C}let g=await this.collectStreamResponse(m.data),h=Date.now()-u;return xe.llmResponse("anthropic",h,g.usage,g.choices[0]),this.debugLog("Response",{duration:`${h}ms`,usage:g.usage}),g}catch(u){await this.normalizeAxiosStreamError(u),o=u;let d=Zt(u);if(d.code==="PROXY_UPSTREAM_FAILED"){let v=JSON.stringify(c||{}).length,b=Array.isArray(e)?e.length:0,C=Array.isArray(e)?e.reduce((T,w)=>w?.content?typeof w.content=="string"?T+w.content.length:Array.isArray(w.content)?T+w.content.map(E=>typeof E.text=="string"?E.text.length:0).reduce((E,N)=>E+N,0):T:T,0):0;p.warn("Anthropic","Upstream request failed (PROXY_UPSTREAM_FAILED)",{attempt:`${a+1}/${r+1}`,payloadSize:v,msgCount:b,promptChars:C,status:u.response?.status});}if(this.debugLog("Error",{message:u.message,category:d.category,code:d.code,attempt:`${a+1}/${r+1}`}),xe.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:a+1}),p.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(!d.retryable||a===r)throw d;let m=ma(u.response?.headers),g=So(d.category,a+1,m||d.retryAfter),h=d.category==="retryable_rate_limit",f=h?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${$t(g)} \u540E\u91CD\u8BD5...`:`Retrying in ${$t(g)}...`;this.debugLog("Retrying",{delay:$t(g),attempt:a+1,isRateLimit:h,serverDelay:m?$t(m):"none",retryMsg:f});try{await Er(g,n.signal);}catch(v){throw v?.name==="AbortError"&&this.debugLog("Chat retry interrupted by user"),v}}}throw o||new Error("Unknown error during retry")}async collectStreamResponse(e){let t="",n="",r=[],o="",i=null,a="";for await(let c of e){let u=c.toString();t+=u;let d=t.split(`
|
|
1943
1943
|
`);t=d.pop()||"";for(let m of d){let g=m.trim();if(!g||!g.startsWith("data: "))continue;let h=g.slice(6);if(h!=="[DONE]")try{let f=JSON.parse(h);if(process.env.CLI_DEBUG==="1"){let v=JSON.stringify(f).substring(0,80);p.debug("SSE",`${f.type.padEnd(20)} ${v}${JSON.stringify(f).length>80?"...":""}`);}switch(f.type){case "message_start":a=f.message?.id||"",i=f.message?.usage;break;case "content_block_start":if(f.content_block?.type==="tool_use"){let v=f.content_block,b=this.isProxyMode?cp[v.name]||this.fromClaudeCodeToolName(v.name):v.name;r.push({id:v.id,type:"function",function:{name:b,arguments:""}});}break;case "content_block_delta":f.delta?.type==="text_delta"?n+=f.delta.text||"":f.delta?.type==="input_json_delta"?r.length>0&&(r[r.length-1].function.arguments+=f.delta.partial_json||""):f.delta?.type==="thinking_delta"&&(o+=f.delta.thinking||"");break;case "message_delta":f.usage&&(i={...i,...f.usage});break}}catch(f){process.env.CLI_DEBUG==="1"&&p.warn("Anthropic",`Stream parse error: ${f}, data: ${h.substring(0,200)}`);}}}let l=this.buildUsageFromRaw(i);return {id:a,choices:[{message:{role:"assistant",content:n||"",tool_calls:r.length>0?r:void 0,...o?{reasoning_content:o}:{}},finish_reason:r.length>0?"tool_calls":"stop"}],usage:l}}async*chatStreamed(e,t={}){let n={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},r=this.retryConfig.streamMaxRetries,o=0,i=n.disableCaching||false,a=true;for(;;){let l={...n,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);c.stream=true,a&&(this.logRequest(t.model||this.defaultModel,c,true),a=false);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",m=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(this.debugLog("Stream started",{status:m.status}),m.status!==200){let P="";for await(let O of m.data)P+=O.toString();let j=`${this.baseUrl}${d}`,z=Fn(j,this.buildHeaders(),c,!1);p.error("CURL","=== [chatStreamed] API Error - Full Request CURL ==="),p.error("CURL",z),p.error("CURL",`=== Error Headers: ${Xy(m.headers)} ===`),p.error("CURL",`=== Error Response: ${P.substring(0,1e3)} ===`);let A=new Error(`Anthropic API error: ${m.status}`);A.response={status:m.status,headers:m.headers,data:P};try{let O=JSON.parse(P);A.response.data=O,O.error?.message?A.message=`Anthropic API error: ${m.status} - ${O.error.message}`:O.message&&(A.message=`Anthropic API error: ${m.status} - ${O.message}`),this.debugLog("API Error Details (stream)",O);}catch{this.debugLog("API Error (non-JSON, stream)",{status:m.status,dataLength:P.length});}throw A}let g="",h=[],f=0,v=!1,b=null,C=!1,T=Date.now(),w=0,E=0,N=null,D=null,$=[],k=null;for await(let P of this.createTimeoutStream(m.data,t.signal)){T=Date.now();let j=P.toString();g+=j;let z=g.split(/\n\n+/);g=z.pop()||"";for(let A of z){let O=A.split(`
|
|
1944
|
-
`),F="";for(let U of O){let K=U.trim();if(K&&!K.startsWith("event:"))if(K.startsWith("data:")){let de=K.slice(5);de.startsWith(" ")&&(de=de.slice(1)),F+=de;}else F+=K;}if(!(!F||F==="[DONE]"))try{let U=F.trim(),K=JSON.parse(U);if(process.env.CLI_DEBUG==="1"){let H=JSON.stringify(K).substring(0,80);p.debug("SSE",`${K.type.padEnd(20)} ${H}${JSON.stringify(K).length>80?"...":""}`);}let de=Date.now(),W=this.handleStreamEvent(K,h,f,v,b);if(process.env.CLI_DEBUG==="1"){let H=Date.now()-de;H>50&&p.warn("SSE",`\u26A0\uFE0F Slow event handling: ${K.type} took ${H}ms`);}if(W.yield){let H=Date.now();if(yield W.yield,process.env.CLI_DEBUG==="1"){let
|
|
1944
|
+
`),F="";for(let U of O){let K=U.trim();if(K&&!K.startsWith("event:"))if(K.startsWith("data:")){let de=K.slice(5);de.startsWith(" ")&&(de=de.slice(1)),F+=de;}else F+=K;}if(!(!F||F==="[DONE]"))try{let U=F.trim(),K=JSON.parse(U);if(process.env.CLI_DEBUG==="1"){let H=JSON.stringify(K).substring(0,80);p.debug("SSE",`${K.type.padEnd(20)} ${H}${JSON.stringify(K).length>80?"...":""}`);}let de=Date.now(),W=this.handleStreamEvent(K,h,f,v,b);if(process.env.CLI_DEBUG==="1"){let H=Date.now()-de;H>50&&p.warn("SSE",`\u26A0\uFE0F Slow event handling: ${K.type} took ${H}ms`);}if(W.yield){let H=Date.now();if(yield W.yield,process.env.CLI_DEBUG==="1"){let ne=Date.now()-H;ne>100&&p.warn("SSE",`\u26A0\uFE0F Slow yield consumer: ${K.type} yield took ${ne}ms`);}}if(W.roleSent!==void 0&&(v=W.roleSent),W.incrementToolIndex&&f++,W.usage&&(b=W.usage),W.error)throw new Error(W.error);W.contentBlockStart&&(E++,W.blockType&&(D=W.blockType)),W.contentBlockStop&&(w++,D==="thinking"&&(yield {choices:[{delta:{reasoning_complete:!0},index:0}]}),D=null),W.messageStop&&(C=!0),W.stopReason&&(N=W.stopReason),K.type==="content_block_start"?K.content_block?.type==="thinking"?k={type:"thinking",thinking:"",signature:""}:K.content_block?.type==="redacted_thinking"&&$.push({type:"redacted_thinking",data:K.content_block.data}):K.type==="content_block_delta"?k&&(K.delta?.type==="thinking_delta"?k.thinking+=K.delta.thinking||"":K.delta?.type==="signature_delta"&&(k.signature+=K.delta.signature||"")):K.type==="content_block_stop"&&k&&($.push({type:k.type,thinking:k.thinking,signature:k.signature}),k=null);}catch{}}}let M=Date.now()-u;if(this.debugLog("Stream completion check",{messageStopReceived:C,stopReason:N,contentBlocksStarted:E,contentBlocksCompleted:w,toolCallsCount:h.length,duration:`${M}ms`}),!C&&!N){let P=new Error(`Stream incomplete: message_stop not received (blocks: ${E} started, ${w} completed)`);throw P.code="STREAM_INCOMPLETE",P.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:C,stopReason:N,contentBlocksStarted:E,contentBlocksCompleted:w,toolCallsCount:h.length,duration:`${M}ms`}),P}if(E!==w)if(N==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:E,contentBlocksCompleted:w,stopReason:N}),p.warn("Anthropic","\u26A0\uFE0F Response truncated due to max_tokens limit. Consider increasing max_tokens or breaking down the task.");else {let P=new Error(`Stream incomplete: content blocks mismatch (${E} started, ${w} completed)`);throw P.code="STREAM_INCOMPLETE",P.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:E,contentBlocksCompleted:w,stopReason:N}),P}if(h.length>0&&N!=="max_tokens")for(let P of h){let j=P.function?.arguments||"";if(j&&j.trim())try{JSON.parse(j);}catch{let z=new Error(`Stream incomplete: tool arguments truncated for ${P.function?.name}`);throw z.code="STREAM_INCOMPLETE",z.isNetworkInterrupt=!0,z.toolName=P.function?.name,this.debugLog("Tool arguments truncated",{toolName:P.function?.name,argsLength:j.length,argsPreview:j.substring(0,100)}),z}}else if(N==="max_tokens"&&h.length>0){let P=h[h.length-1],j=P?.function?.arguments||"";try{JSON.parse(j);}catch{this.debugLog("Tool arguments truncated due to max_tokens (expected)",{toolName:P?.function?.name,argsLength:j.length}),p.warn("Anthropic",`\u26A0\uFE0F Tool call ${P?.function?.name} arguments truncated due to max_tokens. The tool call will be incomplete.`);}}this.debugLog("finalUsage before build",b);let _=this.buildUsageFromRaw(b);this.debugLog("usage after build",_),!v&&h.length===0&&p.warn("Anthropic",`\u26A0\uFE0F Stream completed with no content! duration: ${M}ms, usage: ${JSON.stringify(b)}`),xe.llmResponse("anthropic-stream",M,_||{},{}),this.debugLog("Stream complete",{duration:`${M}ms`}),yield {choices:[{delta:{},finish_reason:"stop",index:0}],..._?{usage:_}:{},...$.length>0?{thinking_blocks:$}:{}};return}catch(u){await this.normalizeAxiosStreamError(u);let d=Zt(u);this.debugLog("Stream error",{message:u.message,category:d.category,retryable:d.retryable});let m=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",g=`${this.baseUrl}${m}`,h=Fn(g,this.buildHeaders(),c,false);if(p.error("CURL","=== [chatStreamed catch] Stream Error - Full Request CURL ==="),p.error("CURL",h),p.error("CURL",`=== Error: ${d.message} ===`),xe.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:o+1}),p.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<r){o++;let f=ma(u.response?.headers),v=So(d.category,o,f||d.retryAfter),b=d.category==="retryable_rate_limit",C=d.category==="retryable_stream";this.debugLog("Stream retrying",{delay:$t(v),attempt:`${o}/${r}`,isRateLimit:b,isStreamIncomplete:C}),yield {type:"stream_retry",error:d.message,errorCode:d.code,attempt:o,maxRetries:r,delayMs:v,isRateLimit:b,isNetworkError:C};try{await Er(v,t.signal);}catch(T){throw T?.name==="AbortError"&&this.debugLog("Stream retry interrupted by user"),T}this.debugLog("Stream retry starting",{attempt:o}),yield {type:"stream_recovered",attempt:o,maxRetries:r};continue}throw d}}}buildPayload(e,t){let n=t.model||this.defaultModel,{system:r,anthropicMessages:o}=this.convertMessages(e,t),i=o,a=[];if(t.disableCaching?(a.push({type:"text",text:lp}),r&&a.push({type:"text",text:`
|
|
1945
1945
|
`+r})):(a.push({type:"text",text:lp,cache_control:{type:"ephemeral"}}),r&&a.push({type:"text",text:`
|
|
1946
1946
|
`+r,cache_control:{type:"ephemeral"}})),process.env.CLI_DEBUG==="1"&&r){let c=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"],u=c.some(g=>r.includes(g)),d=c.reduce((g,h)=>g>=0?g:r.indexOf(h),-1),m=d>=0?r.slice(d,d+300):void 0;p.info("MEMORY_INJECT","Anthropic system memory check",{hasMemory:u,systemLength:r.length,snippet:m});}let l={model:this.normalizeModelName(n),system:a,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(n,t)&&(l.thinking=this.buildThinkingPayload(t),delete l.temperature,l.temperature=1),this.checkRequestBudget(l),l}checkRequestBudget(e){let n=JSON.stringify(e).length;if(n>vi){if(this.debugLog("Request body exceeds limit",{bodySize:n,limit:vi,messageCount:e.messages?.length||0}),e.messages){let o=[...e.messages.map((i,a)=>({index:a,role:i.role,contentSize:JSON.stringify(i.content||"").length}))].sort((i,a)=>a.contentSize-i.contentSize);this.debugLog("Largest messages in request",{top5:o.slice(0,5)});}console.warn(`[Anthropic] \u26A0\uFE0F Request body size (${(n/1024/1024).toFixed(2)}MB) exceeds ${(vi/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else n>EI&&this.debugLog("Request body approaching limit",{bodySize:n,limit:vi,percentage:(n/vi*100).toFixed(1)+"%"});}mergeSystemIntoMessages(e,t){let n=[...t],r=n.findIndex(o=>o.role==="user");if(r>=0){let o=n[r],i={type:"text",text:`<system_context>
|
|
1947
1947
|
${e}
|
|
@@ -1991,9 +1991,9 @@ Your primary responsibilities:
|
|
|
1991
1991
|
1. **Accuracy first**: ensure correctness
|
|
1992
1992
|
2. **Be concise**: avoid redundancy
|
|
1993
1993
|
3. **Safety first**: avoid destructive actions
|
|
1994
|
-
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}};Z();function NI(s){let e="/v1beta/models";if(!s)return e;let t=s.trim();if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return n=n.replace(/\/+$/,""),n.includes("/models")||(n=`${n}/models`),n}function LI(s){try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{value:e}}catch{return {}}}function nb(s){if(s==null)return "{}";if(typeof s=="string"){let e=s.trim();return e?e.startsWith("{")||e.startsWith("[")?e:JSON.stringify({value:e}):"{}"}try{return JSON.stringify(s)}catch{return "{}"}}var OI="skip_thought_signature_validator",rb=8192;function sb(s){return s.includes("gemini-3")||s.includes("preview")}function $I(s){let e=-1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.role==="user"&&r.parts?.some(o=>o.text)){e=n;break}}if(e===-1)return s;let t=s.slice();for(let n=e;n<t.length;n++){let r=t[n];if(r.role==="model"&&r.parts){let o=r.parts.slice();for(let i=0;i<o.length;i++){let a=o[i];if(a.functionCall){a.thoughtSignature||(o[i]={...a,thoughtSignature:OI},t[n]={...r,parts:o});break}}}}return t}var zs=class{client;apiKey;baseURL;pathPrefix;userId;retryConfig;authMode;thinkingSettings=null;constructor(e,t="https://generativelanguage.googleapis.com",n,r){this.apiKey=e,this.baseURL=t.replace(/\/$/,""),this.pathPrefix=NI(r?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(r?.authMode),this.retryConfig=ar(os("gemini"),n);let o={"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${gi__default.platform()}; ${gi__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"?o["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(o.Authorization=`Bearer ${this.apiKey}`),this.client=CI.create({baseURL:this.baseURL,timeout:6e5,headers:o});}resolveAuthMode(e){if(e&&e!=="auto")return e;let t=this.baseURL.includes("generativelanguage.googleapis.com"),n=this.apiKey.startsWith("AIza");return t||n?"query":"bearer"}setThinking(e){this.thinkingSettings=e,process.env.CLI_DEBUG==="1"&&se("GEMINI","Thinking config updated",{config:e});}getThinking(){return this.thinkingSettings}convertMessages(e){let t=this.filterIncompleteToolCalls(e),n=[],r=[],o=[],i=()=>{o.length>0&&(r.push({parts:o,role:"user"}),o=[]);};for(let l of t)if(l.role==="system"){let c=Ce(l.content);c&&n.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 m=d.match(/^data:([^;]+);base64,(.+)$/);m&&c.push({inlineData:{mimeType:m[1],data:m[2]}});}}}r.push({parts:c,role:"user"});}else if(l.role==="assistant"){i();let c=[],u=Ce(l.content);if(u&&c.push({text:u}),l.tool_calls)for(let d of l.tool_calls){let m={functionCall:{name:d.function.name,args:LI(d.function.arguments),id:d.id}};d.thoughtSignature&&(m.thoughtSignature=d.thoughtSignature),c.push(m);}r.push({parts:c,role:"model"});}else if(l.role==="tool"){let c=Ce(l.content)||"",d={name:l.name||"unknown",response:{output:c}};l.tool_call_id&&(d.id=l.tool_call_id),o.push({functionResponse:d});}i();let a={contents:r};return n.length>0&&(a.systemInstruction={parts:n.map(l=>({text:l})),role:"user"}),a}filterIncompleteToolCalls(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.role==="system"){t.push(r),n++;continue}if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){let o=r.tool_calls,i=o.length,a=o.every(h=>!!h.id),l=[],c=[],u=n+1;for(;u<e.length;){let h=e[u];if(h.role==="system"){l.push(h),u++;continue}if(h.role!=="tool")break;l.push(h),c.push(h),u++;}let d=c.length,m=c.every(h=>!!h.tool_call_id),g=d===i;if(g&&a&&m){let h=new Set(c.map(f=>f.tool_call_id).filter(f=>!!f));for(let f of o)if(!h.has(f.id)){g=false;break}}if(g){t.push(r);for(let h of l)t.push(h);}else {process.env.CLI_DEBUG==="1"&&p.debug("GEMINI","Filtering incomplete tool call turn",{toolCalls:o.map(h=>({id:h.id,name:h.function.name})),responseCount:d});for(let h of l)h.role==="system"&&t.push(h);}n=u;continue}if(r.role==="tool"){process.env.CLI_DEBUG==="1"&&p.debug("GEMINI","Dropping orphan tool message",{toolCallId:r.tool_call_id,toolName:r.name}),n++;continue}t.push(r),n++;}return t}convertTools(e){return !e||e.length===0?[]:[{functionDeclarations:e.map(n=>({name:n.name,description:n.description,parameters:{type:n.parameters.type,properties:n.parameters.properties,required:n.parameters.required,additionalProperties:n.parameters.additionalProperties},parametersJsonSchema:{type:n.parameters.type,properties:n.parameters.properties,required:n.parameters.required,additionalProperties:n.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??rb,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 n=e.candidates[0];if(!n)throw new Error("No candidate in Gemini response");let r=n.content?.parts||[],o=null,i=[];for(let c of r)c.text?o=(o||"")+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:nb(c.functionCall.args)}});let a=e.usageMetadata||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0},l=n.finishReason==="STOP"?i.length>0?"tool_calls":"stop":(n.finishReason||"stop").toLowerCase();return {id:t,choices:[{message:{role:"assistant",content:o,tool_calls:i.length>0?i:void 0},finish_reason:l}],usage:{prompt_tokens:a.promptTokenCount,completion_tokens:a.candidatesTokenCount,total_tokens:a.totalTokenCount,cached_tokens:a.cachedContentTokenCount}}}async makeRequest(e,t){let n,r=0;for(;r<=this.retryConfig.requestMaxRetries;)try{return await e()}catch(o){n=o,r++;let i=Zt(o),a=Gn(o.response?.headers?.["retry-after"]);if(!i.retryable||r>this.retryConfig.requestMaxRetries)break;let l=lr(a,r,this.retryConfig);await ls(l);}throw n}async chat(e,t){let n=t.model||"gemini-2.5-flash",{contents:r,systemInstruction:o}=this.convertMessages(e),i=this.convertTools(t.tools||[]),a=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens}),l={contents:r,systemInstruction:o,generationConfig:a};i.length>0&&(l.tools=i);let c=`gemini-${Date.now()}`,u=`${this.pathPrefix}/${n}:generateContent`,d=this.authMode==="query"?{key:this.apiKey}:void 0;return this.makeRequest(async()=>{let m=await this.client.post(u,l,{params:d,signal:t.signal});return this.convertResponse(m.data,c)},"chat")}async*chatStreamed(e,t){let n=t.model||"gemini-2.5-flash",{contents:r,systemInstruction:o}=this.convertMessages(e),i=this.convertTools(t.tools||[]),a=sb(n),l=this.thinkingSettings?.type==="enabled",c=this.thinkingSettings?.type==="disabled",u=t.enableThinking!==void 0?t.enableThinking:l?true:c?false:a,d=t.thinkingBudget??this.thinkingSettings?.budget??rb,m=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens,enableThinking:u,thinkingBudget:d}),h={contents:sb(n)?$I(r):r,systemInstruction:o,generationConfig:m};i.length>0&&(h.tools=i);let f=`gemini-${Date.now()}`,v=`${this.pathPrefix}/${n}:streamGenerateContent`,b=`${this.baseURL}${v}`,C=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"},T=new URL(b);for(let[D,$]of Object.entries(C))T.searchParams.append(D,$);let w={"Content-Type":"application/json",Accept:"*/*"};if(this.authMode==="header"?w["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(w.Authorization=`Bearer ${this.apiKey}`),process.env.CLI_DEBUG==="1"){p.info("GEMINI","=== Gemini Stream Request ==="),p.info("GEMINI",`URL: ${T.toString()}`),p.info("GEMINI",`Model: ${n}`),p.info("GEMINI",`AuthMode: ${this.authMode}`),p.info("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),p.info("GEMINI",`Contents: ${r.length} messages`);let D=Fn(T.toString(),w,h);p.info("GEMINI_CURL",D),p.debug("GEMINI","Request body:",{contentsCount:h.contents.length,hasSystemInstruction:!!h.systemInstruction,toolsCount:h.tools?.[0]?.functionDeclarations?.length||0,generationConfig:h.generationConfig});}if(process.env.CLI_DEBUG==="1"){se("GEMINI","[Gemini Stream Request]"),se("GEMINI",`URL: ${T.toString()}`),se("GEMINI",`Model: ${n}`),se("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),se("GEMINI",`Contents: ${r.length} messages`);let D=Fn(T.toString(),w,h);se("GEMINI_CURL",D);}let E=Date.now(),N=await this.makeRequest(async()=>{let D=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"};return await this.client.post(v,h,{params:D,responseType:"stream",signal:t.signal,headers:{Accept:"*/*","Accept-Language":"*","sec-fetch-mode":"cors","Accept-Encoding":"br, gzip, deflate"}})},"chatStreamed");process.env.CLI_DEBUG==="1"&&(se("GEMINI","[Gemini Stream Started]"),se("GEMINI",`Status: ${N.status}`)),yield*this.streamGenerator(N.data,f,E);}async*streamGenerator(e,t,n){let r="",o=[],i="",a=[],l,c=u=>{let d=[],m=u.candidates?.[0];if(!m)return process.env.CLI_DEBUG==="1"&&se("GEMINI",`No candidate in response: ${JSON.stringify(u).slice(0,200)}`),d;u.usageMetadata&&(l=u.usageMetadata);let g=m.content?.parts;if(!g||g.length===0)process.env.CLI_DEBUG==="1"&&se("GEMINI",`No parts in candidate: ${JSON.stringify(m).slice(0,200)}`);else for(let h of g){if(h.thought&&!h.thoughtSignature&&h.text){process.env.CLI_DEBUG==="1"&&se("GEMINI",`Yielding reasoning: ${h.text.slice(0,50)}...`),d.push({choices:[{index:0,delta:{reasoning_content:h.text}}]});continue}if(h.text)h.thoughtSignature&&process.env.CLI_DEBUG==="1"?se("GEMINI",`Yielding final answer (with signature): ${h.text.slice(0,100)}...`):process.env.CLI_DEBUG==="1"&&se("GEMINI",`Yielding content: ${h.text.slice(0,100)}...`),i+=h.text,d.push({choices:[{index:0,delta:{content:h.text}}]});else if(h.functionCall){let f={id:h.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:h.functionCall.name,arguments:nb(h.functionCall.args)},...h.thoughtSignature?{thoughtSignature:h.thoughtSignature}:{}};a.push(f),d.push({choices:[{index:0,delta:{tool_calls:[{index:a.length-1,id:f.id,type:"function",function:{name:f.function.name,arguments:f.function.arguments},...f.thoughtSignature?{thoughtSignature:f.thoughtSignature}:{}}]}}]});}}if(m.finishReason){let h=l||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};if(process.env.CLI_DEBUG==="1"){let v=n?Date.now()-n:0;p.info("GEMINI","=== Gemini Stream Complete ==="),p.info("GEMINI",`Duration: ${v}ms`),p.info("GEMINI",`Finish Reason: ${m.finishReason}`),p.info("GEMINI",`Tool Calls: ${a.length}`),p.info("GEMINI",`Accumulated Content Length: ${i.length}`),p.info("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),i&&p.info("GEMINI",`Content Preview: ${i.slice(0,500)}...`),a.length>0&&p.info("GEMINI","Tool Calls Detail:",a.map(b=>({id:b.id,name:b.function.name,argsLength:b.function.arguments.length})));}if(process.env.CLI_DEBUG==="1"){let v=n?Date.now()-n:0;se("GEMINI","[Gemini Stream Complete]"),se("GEMINI",`Duration: ${v}ms`),se("GEMINI",`Finish Reason: ${m.finishReason}`),se("GEMINI",`Tool Calls: ${a.length}`),se("GEMINI",`Accumulated Content Length: ${i.length}`),se("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),i&&se("GEMINI",`Content Preview: ${i.slice(0,500)}`);}let f=m.finishReason==="STOP"?a.length>0?"tool_calls":"stop":m.finishReason.toLowerCase();d.push({id:t,choices:[{index:0,delta:{},finish_reason:f}],usage:{prompt_tokens:h.promptTokenCount,completion_tokens:h.candidatesTokenCount,total_tokens:h.totalTokenCount,cached_tokens:h.cachedContentTokenCount}});}return d};try{for await(let u of e){let d=u.toString();r+=d,process.env.CLI_DEBUG==="1"&&se("GEMINI",`Raw chunk (${d.length} bytes): ${d.slice(0,200)}...`);let m=r.split(/\r?\n/);r=m.pop()||"";for(let g of m){let h=g.trimEnd();if(!h){if(o.length===0)continue;let v=o.join(`
|
|
1995
|
-
`);o=[];let b=this.parseSSELine(v);if(!b){process.env.CLI_DEBUG==="1"&&v.length>0&&
|
|
1996
|
-
`));if(u)for(let d of c(u))yield d;}}catch(u){if(process.env.CLI_DEBUG==="1"){let d=n?Date.now()-n:0;
|
|
1994
|
+
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}};Z();function NI(s){let e="/v1beta/models";if(!s)return e;let t=s.trim();if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return n=n.replace(/\/+$/,""),n.includes("/models")||(n=`${n}/models`),n}function LI(s){try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{value:e}}catch{return {}}}function nb(s){if(s==null)return "{}";if(typeof s=="string"){let e=s.trim();return e?e.startsWith("{")||e.startsWith("[")?e:JSON.stringify({value:e}):"{}"}try{return JSON.stringify(s)}catch{return "{}"}}var OI="skip_thought_signature_validator",rb=8192;function sb(s){return s.includes("gemini-3")||s.includes("preview")}function $I(s){let e=-1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.role==="user"&&r.parts?.some(o=>o.text)){e=n;break}}if(e===-1)return s;let t=s.slice();for(let n=e;n<t.length;n++){let r=t[n];if(r.role==="model"&&r.parts){let o=r.parts.slice();for(let i=0;i<o.length;i++){let a=o[i];if(a.functionCall){a.thoughtSignature||(o[i]={...a,thoughtSignature:OI},t[n]={...r,parts:o});break}}}}return t}var zs=class{client;apiKey;baseURL;pathPrefix;userId;retryConfig;authMode;thinkingSettings=null;constructor(e,t="https://generativelanguage.googleapis.com",n,r){this.apiKey=e,this.baseURL=t.replace(/\/$/,""),this.pathPrefix=NI(r?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(r?.authMode),this.retryConfig=ar(os("gemini"),n);let o={"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${gi__default.platform()}; ${gi__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"?o["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(o.Authorization=`Bearer ${this.apiKey}`),this.client=CI.create({baseURL:this.baseURL,timeout:6e5,headers:o});}resolveAuthMode(e){if(e&&e!=="auto")return e;let t=this.baseURL.includes("generativelanguage.googleapis.com"),n=this.apiKey.startsWith("AIza");return t||n?"query":"bearer"}setThinking(e){this.thinkingSettings=e,process.env.CLI_DEBUG==="1"&&oe("GEMINI","Thinking config updated",{config:e});}getThinking(){return this.thinkingSettings}convertMessages(e){let t=this.filterIncompleteToolCalls(e),n=[],r=[],o=[],i=()=>{o.length>0&&(r.push({parts:o,role:"user"}),o=[]);};for(let l of t)if(l.role==="system"){let c=Ce(l.content);c&&n.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 m=d.match(/^data:([^;]+);base64,(.+)$/);m&&c.push({inlineData:{mimeType:m[1],data:m[2]}});}}}r.push({parts:c,role:"user"});}else if(l.role==="assistant"){i();let c=[],u=Ce(l.content);if(u&&c.push({text:u}),l.tool_calls)for(let d of l.tool_calls){let m={functionCall:{name:d.function.name,args:LI(d.function.arguments),id:d.id}};d.thoughtSignature&&(m.thoughtSignature=d.thoughtSignature),c.push(m);}r.push({parts:c,role:"model"});}else if(l.role==="tool"){let c=Ce(l.content)||"",d={name:l.name||"unknown",response:{output:c}};l.tool_call_id&&(d.id=l.tool_call_id),o.push({functionResponse:d});}i();let a={contents:r};return n.length>0&&(a.systemInstruction={parts:n.map(l=>({text:l})),role:"user"}),a}filterIncompleteToolCalls(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.role==="system"){t.push(r),n++;continue}if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){let o=r.tool_calls,i=o.length,a=o.every(h=>!!h.id),l=[],c=[],u=n+1;for(;u<e.length;){let h=e[u];if(h.role==="system"){l.push(h),u++;continue}if(h.role!=="tool")break;l.push(h),c.push(h),u++;}let d=c.length,m=c.every(h=>!!h.tool_call_id),g=d===i;if(g&&a&&m){let h=new Set(c.map(f=>f.tool_call_id).filter(f=>!!f));for(let f of o)if(!h.has(f.id)){g=false;break}}if(g){t.push(r);for(let h of l)t.push(h);}else {process.env.CLI_DEBUG==="1"&&p.debug("GEMINI","Filtering incomplete tool call turn",{toolCalls:o.map(h=>({id:h.id,name:h.function.name})),responseCount:d});for(let h of l)h.role==="system"&&t.push(h);}n=u;continue}if(r.role==="tool"){process.env.CLI_DEBUG==="1"&&p.debug("GEMINI","Dropping orphan tool message",{toolCallId:r.tool_call_id,toolName:r.name}),n++;continue}t.push(r),n++;}return t}convertTools(e){return !e||e.length===0?[]:[{functionDeclarations:e.map(n=>({name:n.name,description:n.description,parameters:{type:n.parameters.type,properties:n.parameters.properties,required:n.parameters.required,additionalProperties:n.parameters.additionalProperties},parametersJsonSchema:{type:n.parameters.type,properties:n.parameters.properties,required:n.parameters.required,additionalProperties:n.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??rb,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 n=e.candidates[0];if(!n)throw new Error("No candidate in Gemini response");let r=n.content?.parts||[],o=null,i=[];for(let c of r)c.text?o=(o||"")+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:nb(c.functionCall.args)}});let a=e.usageMetadata||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0},l=n.finishReason==="STOP"?i.length>0?"tool_calls":"stop":(n.finishReason||"stop").toLowerCase();return {id:t,choices:[{message:{role:"assistant",content:o,tool_calls:i.length>0?i:void 0},finish_reason:l}],usage:{prompt_tokens:a.promptTokenCount,completion_tokens:a.candidatesTokenCount,total_tokens:a.totalTokenCount,cached_tokens:a.cachedContentTokenCount}}}async makeRequest(e,t){let n,r=0;for(;r<=this.retryConfig.requestMaxRetries;)try{return await e()}catch(o){n=o,r++;let i=Zt(o),a=Gn(o.response?.headers?.["retry-after"]);if(!i.retryable||r>this.retryConfig.requestMaxRetries)break;let l=lr(a,r,this.retryConfig);await ls(l);}throw n}async chat(e,t){let n=t.model||"gemini-2.5-flash",{contents:r,systemInstruction:o}=this.convertMessages(e),i=this.convertTools(t.tools||[]),a=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens}),l={contents:r,systemInstruction:o,generationConfig:a};i.length>0&&(l.tools=i);let c=`gemini-${Date.now()}`,u=`${this.pathPrefix}/${n}:generateContent`,d=this.authMode==="query"?{key:this.apiKey}:void 0;return this.makeRequest(async()=>{let m=await this.client.post(u,l,{params:d,signal:t.signal});return this.convertResponse(m.data,c)},"chat")}async*chatStreamed(e,t){let n=t.model||"gemini-2.5-flash",{contents:r,systemInstruction:o}=this.convertMessages(e),i=this.convertTools(t.tools||[]),a=sb(n),l=this.thinkingSettings?.type==="enabled",c=this.thinkingSettings?.type==="disabled",u=t.enableThinking!==void 0?t.enableThinking:l?true:c?false:a,d=t.thinkingBudget??this.thinkingSettings?.budget??rb,m=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens,enableThinking:u,thinkingBudget:d}),h={contents:sb(n)?$I(r):r,systemInstruction:o,generationConfig:m};i.length>0&&(h.tools=i);let f=`gemini-${Date.now()}`,v=`${this.pathPrefix}/${n}:streamGenerateContent`,b=`${this.baseURL}${v}`,C=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"},T=new URL(b);for(let[D,$]of Object.entries(C))T.searchParams.append(D,$);let w={"Content-Type":"application/json",Accept:"*/*"};if(this.authMode==="header"?w["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(w.Authorization=`Bearer ${this.apiKey}`),process.env.CLI_DEBUG==="1"){p.info("GEMINI","=== Gemini Stream Request ==="),p.info("GEMINI",`URL: ${T.toString()}`),p.info("GEMINI",`Model: ${n}`),p.info("GEMINI",`AuthMode: ${this.authMode}`),p.info("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),p.info("GEMINI",`Contents: ${r.length} messages`);let D=Fn(T.toString(),w,h);p.info("GEMINI_CURL",D),p.debug("GEMINI","Request body:",{contentsCount:h.contents.length,hasSystemInstruction:!!h.systemInstruction,toolsCount:h.tools?.[0]?.functionDeclarations?.length||0,generationConfig:h.generationConfig});}if(process.env.CLI_DEBUG==="1"){oe("GEMINI","[Gemini Stream Request]"),oe("GEMINI",`URL: ${T.toString()}`),oe("GEMINI",`Model: ${n}`),oe("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),oe("GEMINI",`Contents: ${r.length} messages`);let D=Fn(T.toString(),w,h);oe("GEMINI_CURL",D);}let E=Date.now(),N=await this.makeRequest(async()=>{let D=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"};return await this.client.post(v,h,{params:D,responseType:"stream",signal:t.signal,headers:{Accept:"*/*","Accept-Language":"*","sec-fetch-mode":"cors","Accept-Encoding":"br, gzip, deflate"}})},"chatStreamed");process.env.CLI_DEBUG==="1"&&(oe("GEMINI","[Gemini Stream Started]"),oe("GEMINI",`Status: ${N.status}`)),yield*this.streamGenerator(N.data,f,E);}async*streamGenerator(e,t,n){let r="",o=[],i="",a=[],l,c=u=>{let d=[],m=u.candidates?.[0];if(!m)return process.env.CLI_DEBUG==="1"&&oe("GEMINI",`No candidate in response: ${JSON.stringify(u).slice(0,200)}`),d;u.usageMetadata&&(l=u.usageMetadata);let g=m.content?.parts;if(!g||g.length===0)process.env.CLI_DEBUG==="1"&&oe("GEMINI",`No parts in candidate: ${JSON.stringify(m).slice(0,200)}`);else for(let h of g){if(h.thought&&!h.thoughtSignature&&h.text){process.env.CLI_DEBUG==="1"&&oe("GEMINI",`Yielding reasoning: ${h.text.slice(0,50)}...`),d.push({choices:[{index:0,delta:{reasoning_content:h.text}}]});continue}if(h.text)h.thoughtSignature&&process.env.CLI_DEBUG==="1"?oe("GEMINI",`Yielding final answer (with signature): ${h.text.slice(0,100)}...`):process.env.CLI_DEBUG==="1"&&oe("GEMINI",`Yielding content: ${h.text.slice(0,100)}...`),i+=h.text,d.push({choices:[{index:0,delta:{content:h.text}}]});else if(h.functionCall){let f={id:h.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:h.functionCall.name,arguments:nb(h.functionCall.args)},...h.thoughtSignature?{thoughtSignature:h.thoughtSignature}:{}};a.push(f),d.push({choices:[{index:0,delta:{tool_calls:[{index:a.length-1,id:f.id,type:"function",function:{name:f.function.name,arguments:f.function.arguments},...f.thoughtSignature?{thoughtSignature:f.thoughtSignature}:{}}]}}]});}}if(m.finishReason){let h=l||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};if(process.env.CLI_DEBUG==="1"){let v=n?Date.now()-n:0;p.info("GEMINI","=== Gemini Stream Complete ==="),p.info("GEMINI",`Duration: ${v}ms`),p.info("GEMINI",`Finish Reason: ${m.finishReason}`),p.info("GEMINI",`Tool Calls: ${a.length}`),p.info("GEMINI",`Accumulated Content Length: ${i.length}`),p.info("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),i&&p.info("GEMINI",`Content Preview: ${i.slice(0,500)}...`),a.length>0&&p.info("GEMINI","Tool Calls Detail:",a.map(b=>({id:b.id,name:b.function.name,argsLength:b.function.arguments.length})));}if(process.env.CLI_DEBUG==="1"){let v=n?Date.now()-n:0;oe("GEMINI","[Gemini Stream Complete]"),oe("GEMINI",`Duration: ${v}ms`),oe("GEMINI",`Finish Reason: ${m.finishReason}`),oe("GEMINI",`Tool Calls: ${a.length}`),oe("GEMINI",`Accumulated Content Length: ${i.length}`),oe("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),i&&oe("GEMINI",`Content Preview: ${i.slice(0,500)}`);}let f=m.finishReason==="STOP"?a.length>0?"tool_calls":"stop":m.finishReason.toLowerCase();d.push({id:t,choices:[{index:0,delta:{},finish_reason:f}],usage:{prompt_tokens:h.promptTokenCount,completion_tokens:h.candidatesTokenCount,total_tokens:h.totalTokenCount,cached_tokens:h.cachedContentTokenCount}});}return d};try{for await(let u of e){let d=u.toString();r+=d,process.env.CLI_DEBUG==="1"&&oe("GEMINI",`Raw chunk (${d.length} bytes): ${d.slice(0,200)}...`);let m=r.split(/\r?\n/);r=m.pop()||"";for(let g of m){let h=g.trimEnd();if(!h){if(o.length===0)continue;let v=o.join(`
|
|
1995
|
+
`);o=[];let b=this.parseSSELine(v);if(!b){process.env.CLI_DEBUG==="1"&&v.length>0&&oe("GEMINI",`Failed to parse event: ${v.slice(0,100)}...`);continue}for(let C of c(b))yield C;continue}if(h.startsWith("data:")){o.push(h.slice(5).trimStart());continue}let f=this.parseSSELine(h);if(!f){process.env.CLI_DEBUG==="1"&&h.length>0&&oe("GEMINI",`Failed to parse line: ${h.slice(0,100)}...`);continue}for(let v of c(f))yield v;}}if(o.length>0){let u=this.parseSSELine(o.join(`
|
|
1996
|
+
`));if(u)for(let d of c(u))yield d;}}catch(u){if(process.env.CLI_DEBUG==="1"){let d=n?Date.now()-n:0;oe("GEMINI","[Gemini Stream Error]"),oe("GEMINI",`Duration: ${d}ms`),oe("GEMINI",`Error: ${u.message||u}`),u.response?.data&&oe("GEMINI",`Response: ${JSON.stringify(u.response.data)}`);}throw u}}};Z();var Bl=class extends Rn{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new $l,this.promptBuilder=new Ci,this.defaultModel=e.defaultModel||"gemini-2.5-flash";let{apiKey:t,baseUrl:n,urlSuffix:r,retry:o}=e;this.provider=new zs(t,n,o,{pathPrefix:r});}prepareRequest(e,t){let n=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:n})}async chat(e,t){let n=this.prepareRequest(e,t);if(!n.validation?.valid){let r=n.validation?.errors||[];throw new Error(`Invalid parameters: ${r.join(", ")}`)}return n.validation?.warnings&&n.validation.warnings.length>0&&p.warn("GeminiAdapter","Warnings",n.validation.warnings),this.provider.chat(n.messages,{model:n.options.model,tools:n.options.tools,temperature:n.options.temperature,structuredOutput:n.options.structuredOutput,maxInputTokens:n.options.maxInputTokens,topP:n.options.topP,topK:n.options.topK,stopSequences:n.options.stopSequences})}async*chatStreamed(e,t){let n=this.prepareRequest(e,t);if(!n.validation?.valid){let r=n.validation?.errors||[];throw new Error(`Invalid parameters: ${r.join(", ")}`)}n.validation?.warnings&&n.validation.warnings.length>0&&p.warn("GeminiAdapter","Warnings",n.validation.warnings),yield*this.provider.chatStreamed(n.messages,{model:n.options.model,tools:n.options.tools,temperature:n.options.temperature,structuredOutput:n.options.structuredOutput,maxInputTokens:n.options.maxInputTokens,topP:n.options.topP,topK:n.options.topK,stopSequences:n.options.stopSequences,signal:t.signal});}getProvider(){return this.provider}};var qs=class s{static createAdapter(e,t){switch(e){case "openai":return s.createOpenAIAdapter(t,false);case "openai-responses":return s.createOpenAIAdapter(t,true);case "kimi":return s.createKimiAdapter(t);case "anthropic":case "anthropic-openai":return s.createAnthropicAdapter(t);case "doubao":throw new Error("Doubao adapter not yet implemented. Use Phase 5.");case "gemini":return s.createGeminiAdapter(t);default:throw new Error(`Unsupported provider protocol: ${e}`)}}static createOpenAIAdapter(e,t){let n={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,useResponsesAPI:t,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new Ml(n)}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 Nl(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 Ol(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 Bl(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 FI=16e3;function UI(s,e=FI){if(!s||s.length<=e)return s;let t=s.split(`
|
|
1997
1997
|
`).length,n=s.length,r=Math.floor(e*.4),o=Math.floor(e*.4),i=r,a=s.length-o;for(;i>0&&(s.charCodeAt(i)&192)===128;)i--;for(;a<s.length&&(s.charCodeAt(a)&192)===128;)a++;let l=s.slice(0,i),c=s.slice(a),d=`
|
|
1998
1998
|
|
|
1999
1999
|
\u2026[${n-l.length-c.length} chars truncated, total ${t} lines]\u2026
|
|
@@ -2054,7 +2054,7 @@ ${e.join(`
|
|
|
2054
2054
|
|
|
2055
2055
|
Provide a comprehensive summary:`}function xi(s){let t=Ce(s.content).length,n=s.tool_calls?JSON.stringify(s.tool_calls).length:0;return Math.ceil((t+n)/4)}function pp(s,e){return s.length<=e?s:s.slice(0,e-1).trimEnd()+"\u2026"}function KI(s){return s.replace(/\s+/g," ").trim()}function dp(s,e){if(s.length===0)return {summary:"",lines:0};let t=[];for(let r of s){if(t.length>=jI)break;let o=r.role==="assistant"?"Assistant":r.role==="user"?"User":r.role,i=Ce(r.content),l=(i?KI(i):"")||(r.tool_calls?.length?`Tool calls: ${r.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${o}] ${pp(l,GI)}`);}return {summary:`${e}
|
|
2056
2056
|
${t.join(`
|
|
2057
|
-
`)}`,lines:t.length}}async function mp(s){let{session:e,profile:t,llmProvider:n,model:r,onProgress:o,timeout:i=6e4,signal:a}=s,l=s.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;o?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((W,H)=>({entry:W,index:H})).filter(({entry:W})=>W.item.type==="message");if(u.length===0)return null;u.filter(({entry:W})=>W.item.data.role==="system");let m=u.filter(({entry:W})=>W.item.data.role!=="system");if(m.length===0)return null;let g=0,h=m.length;for(let W=m.length-1;W>=0;W--){let H=m[W].entry.item.data;if(g+=xi(H),g>=l){h=W;break}}if(h>=m.length){if(m.length<=2)return null;h=Math.floor(m.length/2);}let f=m.slice(0,h).map(({entry:W})=>W.item.data);if(f.length===0)return null;let v={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let W of f){let H=xi(W);W.role==="user"?v.userTokens+=H:W.role==="assistant"?v.assistantTokens+=H:W.role==="tool"&&(v.toolTokens+=H),v.totalTokens+=H;}let b=m.slice(h).map(({entry:W})=>W.item.data),C={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let W of b){let H=xi(W);W.role==="user"?C.userTokens+=H:W.role==="assistant"?C.assistantTokens+=H:W.role==="tool"&&(C.toolTokens+=H),C.totalTokens+=H;}let T=v.totalTokens;o?.("summarizing",`Summarizing ${f.length} messages with AI...`);let w=zI(f),E=w==="zh"?HI:WI,N=qI(f),D,$;try{let W=new AbortController,H=setTimeout(()=>W.abort(),i),
|
|
2057
|
+
`)}`,lines:t.length}}async function mp(s){let{session:e,profile:t,llmProvider:n,model:r,onProgress:o,timeout:i=6e4,signal:a}=s,l=s.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;o?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((W,H)=>({entry:W,index:H})).filter(({entry:W})=>W.item.type==="message");if(u.length===0)return null;u.filter(({entry:W})=>W.item.data.role==="system");let m=u.filter(({entry:W})=>W.item.data.role!=="system");if(m.length===0)return null;let g=0,h=m.length;for(let W=m.length-1;W>=0;W--){let H=m[W].entry.item.data;if(g+=xi(H),g>=l){h=W;break}}if(h>=m.length){if(m.length<=2)return null;h=Math.floor(m.length/2);}let f=m.slice(0,h).map(({entry:W})=>W.item.data);if(f.length===0)return null;let v={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let W of f){let H=xi(W);W.role==="user"?v.userTokens+=H:W.role==="assistant"?v.assistantTokens+=H:W.role==="tool"&&(v.toolTokens+=H),v.totalTokens+=H;}let b=m.slice(h).map(({entry:W})=>W.item.data),C={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let W of b){let H=xi(W);W.role==="user"?C.userTokens+=H:W.role==="assistant"?C.assistantTokens+=H:W.role==="tool"&&(C.toolTokens+=H),C.totalTokens+=H;}let T=v.totalTokens;o?.("summarizing",`Summarizing ${f.length} messages with AI...`);let w=zI(f),E=w==="zh"?HI:WI,N=qI(f),D,$;try{let W=new AbortController,H=setTimeout(()=>W.abort(),i),ne=a?AbortSignal.any([a,W.signal]):W.signal;try{let J=await n.chat([{role:"system",content:E},{role:"user",content:N}],{model:r,temperature:.3,signal:ne});clearTimeout(H),D=Ce(J.choices[0]?.message?.content)||"",$=J.usage?.total_tokens;}catch(J){throw clearTimeout(H),J?.name==="AbortError"||J?.code==="ABORT_ERR"?console.warn("[SmartCompact] LLM call timed out or was cancelled, falling back to lightweight"):console.error("[SmartCompact] LLM call failed:",J.message),J}if(!D.trim()){console.warn("[SmartCompact] LLM returned empty summary, falling back to lightweight");let{summary:J}=dp(f,up);D=J;}}catch(W){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",W.message);let{summary:H}=dp(f,up);D=H;}o?.("saving","Saving compacted history...");let M=`${w==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
|
|
2058
2058
|
|
|
2059
2059
|
${D}`,_=u.length-f.length,P=u[0]?.entry.timestamp??Date.now(),j={item:{type:"message",data:{role:"user",content:M,name:"SmartCompactSummary"}},timestamp:P,seq:0},z={item:{type:"compacted",data:{summary:pp(D,2e3),originalCount:f.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:$}},timestamp:P,seq:0},A=[],O=false,F=new Set(m.slice(0,h).map(({entry:W})=>W));for(let W of c){if(W.item.type!=="message"){A.push({...W});continue}if(W.item.data.role==="system"){A.push({...W});continue}F.has(W)?O||(A.push({...j}),A.push({...z}),O=true):A.push({...W});}if(!O)return null;let U=A.map((W,H)=>({item:W.item,timestamp:W.timestamp??Date.now(),seq:H}));await e.replaceTimeline(U);let K=xi({content:M}),de={before:v,after:{userTokens:C.userTokens,assistantTokens:C.assistantTokens,toolTokens:C.toolTokens,summaryTokens:K,totalTokens:C.totalTokens+K},saved:{userTokens:v.userTokens,assistantTokens:v.assistantTokens,toolTokens:v.toolTokens,totalTokens:v.totalTokens-K}};return {removedMessages:f.length,keptMessages:_,summaryText:M,estimatedTokensSaved:T,llmTokensUsed:$,detailedStats:de}}async function ob(s){let{session:e,profile:t}=s,n=s.tailTokenBudget??t.tailTokenBudget??2e4;if(!n||n<=0)return null;let r=await e.getTimeline(),o=r.map((E,N)=>({entry:E,index:N})).filter(({entry:E})=>E.item.type==="message");if(o.length===0)return null;o.filter(({entry:E})=>E.item.data.role==="system");let a=o.filter(({entry:E})=>E.item.data.role!=="system");if(a.length===0)return null;let l=0,c=a.length;for(let E=a.length-1;E>=0;E--){let N=a[E].entry.item.data;if(l+=xi(N),l>=n){c=E;break}}if(c>=a.length){if(a.length<=2)return null;c=Math.floor(a.length/2);}let u=a.slice(0,c).map(({entry:E})=>E.item.data);if(u.length===0)return null;let{summary:d,lines:m}=dp(u,s.summaryHeader??up);if(!d.trim())return null;let g=a.length-u.length,h=a[0]?.entry.timestamp??Date.now(),f={item:{type:"message",data:{role:"user",content:d,name:"CompatSummary"}},timestamp:h,seq:0},v={item:{type:"compacted",data:{summary:pp(d,2e3),originalCount:u.length,compactedAt:new Date().toISOString()}},timestamp:h,seq:0},b=[],C=false,T=new Set(a.slice(0,c).map(({entry:E})=>E));for(let E of r){if(E.item.type!=="message"){b.push({...E});continue}if(E.item.data.role==="system"){b.push({...E});continue}T.has(E)?C||(b.push({...f}),b.push({...v}),C=true):b.push({...E});}if(!C)return null;let w=b.map((E,N)=>({item:E.item,timestamp:E.timestamp??Date.now(),seq:N}));return await e.replaceTimeline(w),{removedMessages:u.length,keptMessages:g,summaryText:d,summaryLines:m}}var Ul=class{extractFromAssistantMessage(e,t){if(!e||e.length===0)return;let n=[/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 n){let a=e.match(i);if(a){let l=a[2]||a[1];if(l&&l.length>0&&l.length<200)return l.trim()}}let r=t.toLowerCase(),o=e.split(/[.。!!??]/);for(let i of o)if(i.toLowerCase().includes(r)||i.toLowerCase().includes("read")||i.toLowerCase().includes("search")||i.toLowerCase().includes("file")){let a=i.trim();if(a.length>10&&a.length<200)return a}}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()}},jl=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 n=e.pattern||"";t+=` "${this.escapeShellArg(n)}"`;let r=e.path||e.directory||".";return t+=` ${this.escapeShellPath(r)}`,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",n=e.folder||e.path||".";if(t+=` ${this.escapeShellPath(n)}`,e.patterns&&Array.isArray(e.patterns)&&e.patterns.length>0)if(e.patterns.length===1)t+=` -name "${this.escapeShellArg(e.patterns[0])}"`;else {let r=e.patterns.map(o=>`-name "${this.escapeShellArg(o)}"`).join(" -o ");t+=` \\( ${r} \\)`;}return e.excludePatterns&&Array.isArray(e.excludePatterns)&&e.excludePatterns.forEach(r=>{t+=` ! -path "${this.escapeShellArg(r)}"`;}),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 n=e.start_line+e.num_lines-1;return `sed -n '${e.start_line},${n}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 n=e.path||e.directory||e.directory_path||".";return t+=` ${this.escapeShellPath(n)}`,t}generateWriteCommand(e){let t=e.path||e.file_path||e.filename||"",n=e.content||"";return n.length<100&&!n.includes(`
|
|
2060
2060
|
`)?`echo "${this.escapeShellArg(n)}" > ${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 Ks(s,e){let t=["path","file_path","filePath","filename","directory","folder","dir","file","output_path","input_path"];for(let n of t)if(e[n]&&typeof e[n]=="string")return e[n];switch(s){case "Execute":case "execute":if(e.command&&typeof e.command=="string"){let r=e.command,o=r.match(/(?:^|\s)([./~][\w/.-]+\.\w+)(?:\s|$)/);return o?o[1]:r.substring(0,50)+(r.length>50?"...":"")}break;case "search":return e.path||e.directory||".";case "Glob":case "find_files":let n=e.folder||e.path||".";return e.patterns&&Array.isArray(e.patterns)?`${n} (${e.patterns.join(", ")})`:n;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 ib(s,e){switch(s){case "readfile":let t=Ks(s,e);return t?`Reading ${t}`:"Reading file";case "write_file":case "create_file":let n=Ks(s,e);return n?`Writing ${n}`:"Writing file";case "edit_file":case "Edit":let r=Ks(s,e);return r?`Editing ${r}`:"Editing file";case "search":let o=e.pattern||e.query;return o?`Searching for "${o}"`:"Searching code";case "list_directory":case "LS":return `Listing ${Ks(s,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 a=e.command||"";return a.length>60?`Running: ${a.substring(0,60)}...`:`Running: ${a}`;case "read_multiple_files":return e.files&&Array.isArray(e.files)?`Reading ${e.files.length} files`:"Reading multiple files";default:return `Executing ${s}`}}var Gl=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,n,r,o){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:n,startTime:o,args:r}]),{type:"single",merge:false};let a=i[i.length-1];if(o-a.startTime>this.batchTimeWindow)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:n,startTime:o,args:r}]),{type:"single",merge:false};if(i.some(u=>u.targetPath===n))return {type:"single",merge:false};if(i.length===1){let u=this.createBatch(a,e,n,o);return i.push({toolId:e,toolName:t,targetPath:n,startTime:o,args:r}),{type:"batch",merge:false,batchId:u,shouldCreateBatch:true}}else {let u=this.findActiveBatch(t);return u?(i.push({toolId:e,toolName:t,targetPath:n,startTime:o,args:r}),this.updateBatch(u,n,o),{type:"batch",merge:true,batchId:u}):(this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:n,startTime:o,args:r}]),{type:"single",merge:false})}}recordCompletion(e,t){let n=this.findActiveBatch(e);if(n){let r=this.activeBatches.get(n);r&&(r.completed++,r.completed>=r.total&&this.completeBatch(n));}}getBatchInfo(e){return this.activeBatches.get(e)}isBatchable(e){return this.batchableTools.has(e)}createBatch(e,t,n,r){let o=`batch-${e.toolName}-${r}`;return this.activeBatches.set(o,{batchId:o,toolName:e.toolName,targets:[e.targetPath,n],startTime:e.startTime,lastCallTime:r,completed:0,total:2}),o}updateBatch(e,t,n){let r=this.activeBatches.get(e);r&&(r.targets.push(t),r.total++,r.lastCallTime=n);}findActiveBatch(e){for(let[t,n]of this.activeBatches.entries())if(n.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,n=[];this.activeBatches.forEach((o,i)=>{e-o.lastCallTime>t&&n.push(i);}),n.forEach(o=>this.completeBatch(o));let r=[];this.pendingCalls.forEach((o,i)=>{if(o.length>0){let a=o[o.length-1];e-a.startTime>t&&r.push(i);}}),r.forEach(o=>this.pendingCalls.delete(o));}reset(){this.activeBatches.clear(),this.pendingCalls.clear();}getStats(){let e=[];return this.activeBatches.forEach((t,n)=>{e.push({batchId:n,toolName:t.toolName,total:t.total,completed:t.completed});}),{activeBatches:this.activeBatches.size,pendingCalls:this.pendingCalls.size,batches:e}}};Z();function ab(s){if(!s||s.trim().length===0)return null;let e=s.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 r=0,o=0,i=false,a=false;for(let l of e){if(a){a=false;continue}if(l==="\\"){a=true;continue}if(l==='"'){i=!i;continue}i||(l==="{"?r++:l==="}"?r--:l==="["?o++:l==="]"&&o--);}for(i&&(e+='"');o>0;)e+="]",o--;for(;r>0;)e+="}",r--;try{return JSON.parse(e),console.log("[JsonRepair] Fixed by force-closing structures"),e}catch{return null}}function lb(s,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(s==="write_file"||s==="edit_file"){if(!e.includes('"content"')&&!e.includes('"new_string"'))return {isTruncated:true,reason:"File content field is missing - likely truncated during streaming"};let n=e.match(/"content"\s*:\s*"([^]*)/);if(n){let r=n[1],o=0,i=false;for(let a of r){if(i){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){o++;break}}if(o===0)return {isTruncated:true,reason:"Content string is unclosed - truncated during streaming"}}}return {isTruncated:false}}function cb(s,e,t){let n=Rg(s,e,t),r=ga(n);return {success:false,error:n.code,code:n.code,category:n.category,message:n.message,suggestion:r,retryable:n.retryable,receivedArgs:e?.substring(0,500)}}var db=12e3,Wl=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;descriptionExtractor=new Ul;commandGenerator=new jl;lastAssistantMessage="";batchDetector=new Gl;toolCallIdCounter=0;recentToolCalls=new Map;currentTaskMetadata;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=he__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=he__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 n=this.session?.sessionId,r=jf(n,this.sessionSeed);t.setUserId(r);}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;}emitEvent(e){if(e.type==="plan_update"&&p.info("EMIT_EVENT","\u{1F525} Emitting plan_update via eventEmitter",{listenerCount:this.eventEmitter.listenerCount("event"),hasExplanation:!!e.explanation,planSteps:e.plan?.length}),e.type==="text"&&process.env.CLI_DEBUG==="1"){let t=e.delta||"";p.debug("EMIT_EVENT",`Emitting text event: "${t.substring(0,20)}...", listeners=${this.eventEmitter.listenerCount("event")}`);}this.eventEmitter.emit("event",e),e.type==="plan_update"&&p.info("EMIT_EVENT","\u2705 plan_update emitted");}emitLog(e,t,n){process.env.CLI_DEBUG&&(p.debug("EMIT",`emitLog: level=${e}, message="${t.substring(0,50)}..."`),p.debug("EMIT",` eventEmitter.listenerCount: ${this.eventEmitter.listenerCount("event")}`)),this.emitEvent({type:"log",level:e,message:t,detail:n});}emitCompacting(e,t){process.env.CLI_DEBUG&&p.debug("EMIT",`emitCompacting: message="${e.substring(0,50)}..."`),this.emitEvent({type:"compacting",message:e,detail:t});}updateRuntime(e){this.runner=e.runner,this.memory=e.memory,this.model=e.model,e.systemPrompt&&(this.systemPrompt=e.systemPrompt);}setCompressionMode(e){this.compressionMode=e,p.info("RUNTIME",`Compression mode set to: ${e}`);}getCompressionMode(){return this.compressionMode}prepareTaskInput(e,t){let n=e,r=t?.attachments?.filter(o=>o.type==="url")||[];return r.length>0&&(n=`Attachments:
|
|
@@ -2079,9 +2079,9 @@ ${n}`),n.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.
|
|
|
2079
2079
|
User: ${w(T.userTokens)} \u2022 Assistant: ${w(T.assistantTokens)} \u2022 Tool: ${w(T.toolTokens)}`,v+=`
|
|
2080
2080
|
\u51C0\u8282\u7701: ${w(T.totalTokens)}`;}this.emitCompacting("\u2713 \u667A\u80FD\u538B\u7F29\u5B8C\u6210",v),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}else {this.emitCompacting("\u25B8 \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${a}\uFF0C\u4E3A\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF0C\u5C06\u603B\u7ED3\u8F83\u65E7\u7684\u6D88\u606F\u3002`),this.emitEvent({type:"status",status:"compacting",message:"\u25B8 Auto-compacting history..."});let l=await ob({session:i,profile:this.compatProfile});if(!l){this.emitCompacting("\u2139\uFE0F \u65E0\u9700\u538B\u7F29","\u5BF9\u8BDD\u5386\u53F2\u8F83\u77ED\uFF0C\u6240\u6709\u6D88\u606F\u90FD\u5728\u4FDD\u7559\u9884\u7B97\u5185\uFF0820K tokens\uFF09"),this.emitEvent({type:"status",status:"complete",message:"No compaction needed"});return}await this.sessionSync.loadHistory();let c="";if(this.memoryPressure){this.memoryPressure.reset();let g=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(g,!0),g.profile.contextWindow){let h=Math.round(g.tokensUsed/g.profile.contextWindow*100);c=`
|
|
2081
2081
|
\u5F53\u524D\u4E0A\u4E0B\u6587: ${g.tokensUsed.toLocaleString()} / ${g.profile.contextWindow.toLocaleString()} tokens (${h}%)`;}}let d=(await i.getTimeline()).filter(g=>g.item.type==="message"),m=Hn(this.memory.getAll());this.emitEvent({type:"context_compaction",status:"completed",originalMessages:r,keptMessages:d.length,droppedMessages:l.removedMessages,compressedMessages:0,originalTokens:o.totalTokens,finalTokens:m.totalTokens,budgetTokens:t.profile.contextWindow||0,useLLM:!1,timestamp:Date.now()}),this.emitCompacting("\u2713 \u81EA\u52A8\u538B\u7F29\u5B8C\u6210",`\u6458\u8981 ${l.summaryLines} \u884C\uFF0C\u79FB\u9664 ${l.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${l.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\u3002${c}`),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}}catch(i){let a=i?.message||String(i);this.emitLog("error","\u81EA\u52A8\u538B\u7F29\u5931\u8D25",`\u9519\u8BEF\u8BE6\u60C5: ${a}`),process.env.CLI_DEBUG==="1"&&p.error("[COMPACTION] Failed:",i);}finally{this.autoCompactionInProgress=false;}}async runTask(e,t){if(process.env.CLI_DEBUG==="1"&&(p.debug("TASK","========================================"),p.debug("TASK","=== runTask ENTRY ==="),p.debug("TASK",` userInput: "${e?.substring(0,50)}..."`),p.debug("TASK",` isRunning: ${this.isRunning}`),p.debug("TASK",` shouldInterrupt: ${this.shouldInterrupt}`),p.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`),p.debug("TASK",` stdin.destroyed: ${process.stdin.destroyed}`)),this.syncWorkspaceEnv(),!e.trim())throw new Error("Input is required");if(this.shouldInterrupt=false,this.isRunning=true,this.abortController=new AbortController,t?.abortSignal){let C=t.abortSignal;if(C.aborted)this.shouldInterrupt=true,this.abortController.abort();else {let T=()=>{this.shouldInterrupt=true,this.abortController?.abort();};C.addEventListener("abort",T,{once:true});}}let n=t?.metadata?.mode,r=this.runner.getMode(),o=n==="ask"&&r!=="ask";o&&this.runner.setMode("ask");let i=this.prepareTaskInput(e,t?.metadata),a=this.extractImageUrls(t?.metadata);if(this.currentTaskMetadata=t?.metadata,this.sessionSync&&this.sessionEnabled)try{let C=this.sessionSync.getTurnCount()+1,T=await this.sessionSync.createCheckpoint(`turn_${C}`);this.emitEvent({type:"checkpoint",id:T,auto:!0});}catch(C){p.error("TASK","\u68C0\u67E5\u70B9\u521B\u5EFA\u5931\u8D25\uFF01 \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25\uFF01",C),console.error("Failed to create auto checkpoint",C);}this.emitEvent({type:"status",status:"thinking",message:"Starting..."});let l=Date.now(),c="",u=0,d=0,m=0,g="",h="",f="",v=0,b=0;try{let C=this.abortController?.signal;process.env.CLI_DEBUG==="1"&&p.debug("TASK","=== \u5F00\u59CBagent loop \u5FAA\u73AF ===");let T=0,w=this.createInterruptPromise(),E=this.runner.run(i,a.length>0?a:void 0,C)[Symbol.asyncIterator]();for(;;){let k=E.next();k.catch(()=>{});let M=await Promise.race([k,w]);if("interrupted"in M){if(this.shouldInterrupt=!0,E.return)try{E.return(void 0)?.catch?.(()=>{});}catch{}break}if(M.done)break;let _=M.value;if(T++,process.env.CLI_DEBUG==="1"&&p.debug("TASK",` \u4E8B\u4EF6 #${T}: ${_.type}`),this.shouldInterrupt){process.env.CLI_DEBUG==="1"&&p.debug("TASK"," shouldInterrupt=true, \u9000\u51FAloop");break}switch(_.type){case "iteration_start":if(this.emitEvent({type:"text_complete"}),u=_.iteration||0,this.emitEvent({type:"thinking",iteration:u,timestamp:Date.now()}),this.emitEvent({type:"status",status:"thinking",message:`Thinking... (iteration ${u})`}),b=0,this.memoryPressure){let A=this.memory.getMessagesForLLM();process.env.CLI_DEBUG&&(p.debug("CONTEXT",`\u8FED\u4EE3\u5F00\u59CB: \u77ED\u671F\u8BB0\u5FC6 \u6709 ${A.length} \u6D88\u606F`),A.forEach((O,F)=>{let U=typeof O.content=="string"?O.content.length:JSON.stringify(O.content).length;p.debug("CONTEXT",` [${F}] role=${O.role}, content_len=${U}`);}));}break;case "text_delta":if(_.delta){c+=_.delta,g+=_.delta;let A=Math.ceil(_.delta.length/4);b+=A,(_.delta.trim().length>0||_.delta.includes(`
|
|
2082
|
-
`))&&(this.emitEvent({type:"status",status:"thinking",message:"Generating response..."}),this.emitEvent({type:"text",delta:_.delta}));}break;case "reasoning_delta":_.delta&&this.emitEvent({type:"reasoning",delta:_.delta,timestamp:Date.now()});break;case "reasoning_complete":this.emitEvent({type:"reasoning_complete",timestamp:Date.now()});break;case "tool_call_start":d++,h="",v=0,f=_.name||"",this.emitEvent({type:"status",status:"tool_call",message:`Calling: ${_.name}`});break;case "tool_call_delta":if(_.arguments_delta){h+=_.arguments_delta,v+=_.arguments_delta.length;let A=Math.ceil(_.arguments_delta.length/4);if(b+=A,_.arguments_delta.trim().length>0&&this.emitEvent({type:"tool_call_delta",name:f||_.name||"unknown",argumentsDelta:_.arguments_delta}),v>1e3){let K=1-h.trim().length/v;K>.9&&(console.error(`[AgentHost] \u26A0\uFE0F Abnormal tool call: ${f} - ${(K*100).toFixed(1)}% whitespace (${v} bytes)`),this.emitLog("warn",`Model output abnormal: ${f} generating mostly whitespace content`));}if(f==="write_file"||f==="Write"||_.name==="write_file"||_.name==="Write"){let U=Math.floor(v/80),K=(v/1024).toFixed(1);this.emitEvent({type:"status",status:"tool_call",message:`\u26A1 Generating... ${K}KB (~${U} lines)`});try{let de=h.match(/"file_path"\s*:\s*"([^"]+)"/),W=h.match(/"content"\s*:\s*"/);if(de&&W){let H=de[1],
|
|
2083
|
-
`).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ue=H.split(".").pop()||"",
|
|
2084
|
-
`),ve=ae.length<=5;ne.length>2e3&&(ne=ne.slice(-2e3)),ve?this.emitEvent({type:"file_stream",filePath:H,content:ne,language:re[ue]||ue,description:g.trim()||"Generating code...",timestamp:Date.now()}):this.emitEvent({type:"status",status:"tool_call",message:`Writing ${H} (${ae.length} lines)...`});}}}catch{p.error("MK","\u4E0D\u5B8C\u6574\u7684json \u5904\u7406");}}}break;case "tool_call_done":{if(_.name&&_.arguments)try{let A=_.arguments.trim(),O=lb(_.name,A);if(O.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&p.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${O.reason}`);let ne=ab(A);if(ne)process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[AgentHost] \u2705 JSON repaired successfully"),A=ne;else throw new Error(`Tool arguments truncated: ${O.reason}`)}let F=A?JSON.parse(A):{};process.env.CLI_DEBUG_CONSOLE==="1"&&p.debug("TOOL",`\u2705 Tool call parsed: ${_.name}`,{argsLength:A.length});let U=Ks(_.name,F),K=this.descriptionExtractor.extractFromAssistantMessage(g,_.name);K||(K=ib(_.name,F));let de=this.commandGenerator.generateEquivalentCommand(_.name,F),W=`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,H=Date.now(),oe=this.batchDetector.detectBatch(W,_.name,U||"",F,H);this.recentToolCalls.set(_.name,{toolId:W,batchId:oe.batchId,targetPath:U,args:F});let J={targetPath:U,argsPreview:JSON.stringify(F).substring(0,200)};_.name==="search"&&F.pattern?J.pattern=F.pattern.substring(0,80):(_.name==="readfile"||_.name==="edit_file")&&F.path&&(J.file=F.path),p.info("TOOL",`\u{1F916} [AGENT] Call: ${_.name}`,J),this.emitEvent({type:"tool_call_start",name:_.name,args:F,targetPath:U,description:K,equivalentCommand:de,timestamp:H+Math.random()*.1,toolId:W,isBatch:oe.type==="batch",batchId:oe.batchId});let fe=_.name==="write_file"||_.name==="Write",V=F.file_path||F.filePath||F.path;fe&&V&&F.content&&(await this.emitFileStreamEvent(V,F.content,g.trim()||void 0),g="");}catch(A){console.error("[AgentHost] \u274C Failed to parse tool arguments for:",_.name),console.error("[AgentHost] Error:",A.message),console.error("[AgentHost] Arguments length:",_.arguments?.length||0),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.error("[AgentHost] First 200 chars:",_.arguments?.substring(0,200)||""),console.error("[AgentHost] Last 200 chars:",_.arguments?.substring(Math.max(0,(_.arguments?.length||0)-200))||""));let O=cb(_.name,_.arguments||"",A),F=O.category==="tool_truncated"?`\u274C Tool ${_.name}: content truncated during streaming`:`\u274C Tool ${_.name}: ${O.code}`;this.emitEvent({type:"status",status:"error",message:F}),this.emitEvent({type:"tool_call_start",name:_.name,args:{_raw:_.arguments?.substring(0,500)||"",_error:O.code,_errorCategory:O.category,_errorMessage:O.message,_suggestion:O.suggestion,_retryable:O.retryable},timestamp:Date.now()}),this.emitEvent({type:"tool_output",name:_.name,output:JSON.stringify(O),success:!1});}break}case "tool_output":if(_.name&&_.output!==void 0){let A=typeof _.output=="string"?_.output:JSON.stringify(_.output),O=A.length,F=_.success??!0,U=A.slice(0,db),K=A.length>db;p.info("TOOL",`\u{1F916} [AGENT] Result: ${_.name} ${F?"\u2713":"\u2717"}`,{success:F,resultLength:O,outputString:A});let de=this.recentToolCalls.get(_.name),{toolId:W,batchId:H,targetPath:oe,args:J}=de||{},fe=oe||(J&&typeof J.directory=="string"?J.directory:void 0),V=_.name==="show_tree"?`show_tree: ${fe||"."} (${O} chars)`:void 0;if(F&&fe&&this.batchDetector.recordCompletion(_.name,fe),this.emitEvent({type:"tool_call_end",name:_.name,success:F,resultLength:O,timestamp:Date.now()+Math.random()*.1,toolId:W,batchId:H,targetPath:fe,summary:V,output:U,outputTruncated:K,args:J}),_.name==="write_file"&&_.success&&J?.file_path&&J?.content){try{let ne=J.file_path,ue=J.content,re=ne.split(".").pop()?.toLowerCase()||"",ae={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"write_file_stream",filePath:ne,content:ue,isComplete:!0,language:ae[re]||re,timestamp:Date.now()});}catch(ne){p.error("TOOL","write_file_stream \u53D1\u9001\u5931\u8D25",ne);}await this.handleWriteFile(J.file_path,J.content,void 0);}if(_.name==="edit_file"&&_.success&&this.sessionSync&&this.sessionEnabled)try{let ne=JSON.parse(A),ue=ne.metadata?.edit_info||ne.edit_info,re=ne.metadata?.hunks;if(p.info("TOOL","edit file\u7684\u7ED3\u679C "+ne),p.info("TOOL","edit file\u7684editInfo "+ue),ne.status==="success"&&ue){let ae=[];if(Array.isArray(re)&&re.length>0)for(let ee of re)ae.push({type:"file_edit_snapshot",data:{filePath:ne.file_path,oldString:ee.old_string,newString:ee.new_string,startLine:ee.start_line,oldLineCount:ee.old_line_count,newLineCount:ee.new_line_count,replaceAll:!1,replacementCount:1}});else ae.push({type:"file_edit_snapshot",data:{filePath:ne.file_path,oldString:ue.old_string,newString:ue.new_string,startLine:ue.start_line,oldLineCount:ue.old_line_count,newLineCount:ue.new_line_count,replaceAll:(ne.metadata?.replacements||ne.replacements)>1,replacementCount:ne.metadata?.replacements||ne.replacements}});await this.sessionSync.getSession().addItems(ae);}}catch{p.error("TOOL","session\u7684edit file \u4FDD\u5B58\u5931\u8D25 ");}if(_.name==="edit_file"&&_.success)try{let ne=JSON.parse(A),ue=ne.metadata?.edit_info||ne.edit_info;if(ne.status==="success"&&ue){let re=Array.isArray(ne.metadata?.hunks)?ne.metadata.hunks.map(ve=>({oldString:ve.old_string,newString:ve.new_string,startLine:ve.start_line})):void 0,ae=ne.file_path.split(".").pop()?.toLowerCase()||"",ee={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"edit_file_stream",filePath:ne.file_path,oldString:ue.old_string,newString:ue.new_string,startLine:ue.start_line,hunks:re,isComplete:!0,language:ee[ae]||ae,timestamp:Date.now()});}}catch{p.error("TOOL","edit file \u4FDD\u5B58\u5931\u8D25 ");}this.emitEvent({type:"tool_output",name:_.name,output:_.output,success:F});}break;case "token_usage":if(_.usage){m=_.usage.total_tokens;let A=_.usage.prompt_tokens||0,O=_.usage.completion_tokens||0,F=_.usage.prompt_tokens_details?.cached_tokens||0,U=_.usage.cache_read_input_tokens||0,K=_.usage.cache_creation_input_tokens||0,de=F||U||_.usage.cached_tokens||0,W=A+U+K+F;if(p.debug("CACHE","\u{1F525} Cache token calculation:"),p.debug("CACHE",` actualInputTokens=${A}`),p.debug("CACHE",` anthropicCacheReadTokens=${U}`),p.debug("CACHE",` anthropicCacheCreationTokens=${K}`),p.debug("CACHE",` openaiCachedTokens=${F}`),p.debug("CACHE",` fullContextInputTokens=${W}`),p.debug("CACHE",` formula: ${A} + ${U} + ${K} + ${F} = ${W}`),this.sessionTotalInputTokens+=W,this.sessionTotalOutputTokens+=O,process.env.CLI_DEBUG&&(p.debug("CONTEXT","token_usage event received:"),p.debug("CONTEXT",` actualInputTokens=${A}, actualOutputTokens=${O}`),p.debug("CONTEXT",` anthropicCacheReadTokens=${U}, openaiCachedTokens=${F}`),p.debug("CONTEXT",` anthropicCacheCreationTokens=${K}`),p.debug("CONTEXT",` fullContextInputTokens=${W}`),p.debug("CONTEXT",` sessionTotalInput=${this.sessionTotalInputTokens}, sessionTotalOutput=${this.sessionTotalOutputTokens}`),p.debug("CONTEXT",` memoryPressure initialized: ${!!this.memoryPressure}`)),this.memoryPressure){let H=this.memory.getMessagesForLLM(),oe=this.memoryPressure.estimateMessagesForDisplay(H);this.memoryPressure.recordCalibration(oe,A,U);let J=this.memoryPressure.recordActualUsage(W,O,H.length);p.debug("SNAPSHOT","\u{1F525} Snapshot values:"),p.debug("SNAPSHOT",` fullContextInputTokens (passed to recordActualUsage)=${W}`),p.debug("SNAPSHOT",` snapshot.promptTokens (returned)=${J.promptTokens}`),p.debug("SNAPSHOT",` snapshot.tokensUsed=${J.tokensUsed}`),p.debug("SNAPSHOT",` snapshot.pressure=${J.pressure}`),process.env.CLI_DEBUG&&(p.debug("CONTEXT","recordActualUsage snapshot:"),p.debug("CONTEXT",` tokensUsed=${J.tokensUsed}, promptTokens=${J.promptTokens}`),p.debug("CONTEXT",` completionTokens=${J.completionTokens}, contextWindow=${J.profile.contextWindow}`),p.debug("CONTEXT",` pressure=${J.pressure}, state=${J.state}`)),await this.handleMemorySnapshot(J);}b=0,this.emitEvent({type:"token_usage",promptTokens:W,completionTokens:O,totalTokens:W+O,cachedTokens:de>0?de:void 0,openaiCachedTokens:F>0?F:void 0,anthropicCacheReadTokens:U>0?U:void 0,anthropicCacheCreationTokens:K>0?K:void 0,sessionPromptTokens:this.sessionTotalInputTokens,sessionCompletionTokens:this.sessionTotalOutputTokens});}break;case "context_compaction":this.emitEvent({type:"context_compaction",status:_.status,originalMessages:_.originalMessages,keptMessages:_.keptMessages,droppedMessages:_.droppedMessages,compressedMessages:_.compressedMessages,originalTokens:_.originalTokens,finalTokens:_.finalTokens,budgetTokens:_.budgetTokens,useLLM:_.useLLM,timestamp:_.timestamp??Date.now()});break;case "raw_response_event":if(_.event_type==="input_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking input guardrails..."});else if(_.event_type==="output_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking output guardrails..."});else if(_.event_type==="structured_output.retry"){this.emitEvent({type:"text_complete"}),c="";let A=Array.isArray(_.data?.errors)&&_.data.errors.length>0?_.data.errors.join("; "):_.data?.message;this.emitLog("warn","Structured output validation failed",A),this.emitEvent({type:"status",status:"error",message:"Structured output invalid, retrying..."});}else if(_.event_type==="structured_output.accepted")typeof _.data?.normalized_text=="string"&&(c=_.data.normalized_text),this.emitLog("info","Structured output ready",_.data?.schema?`Schema: ${_.data.schema}`:void 0);else if(_.event_type==="error.classified"){let A=_.data;this.emitEvent({type:"error_classified",category:A.category||"INTERNAL",code:A.code||"UNKNOWN_ERROR",message:A.message||"An unknown error occurred",suggestion:A.suggestion,retryable:A.retryable??!1});}else if(_.event_type==="context_compaction"){let A=_.data;if(this.memoryPressure&&A.finalTokens!==void 0){let U=this.memoryPressure.setPromptEstimateFromMessages(this.memory.getMessagesForLLM());this.handleMemorySnapshot(U,!0);}let O=A.droppedMessages||0,F=A.compressedMessages||0;if(O>0||F>0){let U=(A.originalTokens||0)-(A.finalTokens||0),K=A.useLLM?"\u667A\u80FD\u538B\u7F29":"\u88C1\u526A";this.emitLog("info",`\u25B8 \u4E0A\u4E0B\u6587${K}`,`\u79FB\u9664 ${O} \u6761\u6D88\u606F${F>0?`\uFF0C\u538B\u7F29 ${F} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${U.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${O} messages`});}}else _.event_type==="response.completed"&&(process.env.CLI_DEBUG_CONSOLE==="1"&&p.debug("EVENTS","\u{1F4E4} Forwarding response.completed"),this.emitEvent({type:"raw_response_event",data:_.data,event_type:_.event_type}));break;case "run_done":break;case "error":p.error("AGENT",`Error: ${_.error||"Unknown error"}`),this.emitEvent({type:"error",message:_.error||"Unknown error"}),this.emitEvent({type:"status",status:"error",message:`Error: ${_.error||"Unknown error"}`});break;case "stream_retry":let P=_;this.emitEvent({type:"stream_retry",error:P.error,errorCode:P.errorCode||"STREAM_ERROR",attempt:P.attempt,maxRetries:P.maxRetries,delayMs:P.delayMs});break;case "stream_recovered":let j=_;this.emitEvent({type:"stream_recovered",attempt:j.attempt,maxRetries:j.maxRetries});break;case "plan_update":let z=_;p.info("RUNTIME_HOST","\u{1F525} Forwarding plan_update event",{hasExplanation:!!z.explanation,planSteps:z.plan?.length}),this.emitEvent({type:"plan_update",explanation:z.explanation,plan:z.plan,timestamp:z.timestamp||Date.now()});break}}process.env.CLI_DEBUG==="1"&&(p.debug("TASK","=== runner.run loop COMPLETED ==="),p.debug("TASK",` Total events: ${T}`),p.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`)),this.emitEvent({type:"text_complete"});let N=Date.now()-l,D=c;if(this.shouldInterrupt)this.emitEvent({type:"status",status:"error",message:"Task interrupted"});else if(this.emitEvent({type:"status",status:"complete",message:"Complete!"}),this.emitLog("info","Task complete",`${u} iterations, ${d} tool calls, ${m} tokens, ${(N/1e3).toFixed(2)}s`),this.sessionSync&&this.sessionEnabled&&D)try{await this.sessionSync.saveTurn({role:"user",content:i},{role:"assistant",content:D});}catch{}let $={output:D,totalTokens:m,durationMs:N,iterations:u,toolCalls:d,interrupted:this.shouldInterrupt};return this.emitEvent({type:"run_result",output:D,totalTokens:m,iterations:u,toolCalls:d,durationMs:N}),$}catch(C){if(C?.code==="ERR_CANCELED"||C?.name==="CanceledError"||C?.name==="AbortError"||C?.category==="canceled"||this.shouldInterrupt){this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:"Task interrupted"}),this.emitLog("info","Task interrupted by user");let E=Date.now()-l;return {output:c,totalTokens:m,durationMs:E,iterations:u,toolCalls:d,interrupted:true}}let w=C?.message||String(C)||"Unknown error";throw this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:`Error: ${w}`}),this.emitLog("error",`Error: ${w}`),C}finally{process.env.CLI_DEBUG&&(p.debug("TASK","=== runTask finally block START ==="),p.debug("TASK",` isRunning was: ${this.isRunning}`)),o&&this.runner.setMode(r),this.isRunning=false,this.abortController=null,this.clearInterruptPromise(),process.env.CLI_DEBUG&&p.debug("TASK","=== runTask finally block END ===");}}syncWorkspaceEnv(){this.workDir&&(process.env.NEOX_WORKDIR=this.workDir);}async listSessions(){return this.sessionManager.listSessions()}getCurrentSessionId(){return this.session?.sessionId}async getSessionInfo(){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.getSessionInfo()}async emitFileStreamEvent(e,t,n){let r=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[r]||r,a=Date.now();this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:false,language:i,description:n,timestamp:a});}async handleWriteFile(e,t,n){let r=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[r]||r,a=Date.now();try{let l=await import('fs'),c=await import('path'),u=c.isAbsolute(e)?c.resolve(e):c.resolve(this.workDir,e);if(this.sessionSync&&this.sessionEnabled)try{let d=null,m="create";l.existsSync(u)&&(m="modify",d=null);let g={type:"file_snapshot",data:{filePath:e,originalContent:d,operation:m,newContent:t}};await this.sessionSync.getSession().addItems([g]);}catch(d){console.debug("Failed to capture file snapshot",d);}this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:!0,language:i,description:n,timestamp:a}),this.emitLog("info",`\u2713 Saved ${e}`,`${t.split(`
|
|
2082
|
+
`))&&(this.emitEvent({type:"status",status:"thinking",message:"Generating response..."}),this.emitEvent({type:"text",delta:_.delta}));}break;case "reasoning_delta":_.delta&&this.emitEvent({type:"reasoning",delta:_.delta,timestamp:Date.now()});break;case "reasoning_complete":this.emitEvent({type:"reasoning_complete",timestamp:Date.now()});break;case "tool_call_start":d++,h="",v=0,f=_.name||"",this.emitEvent({type:"status",status:"tool_call",message:`Calling: ${_.name}`});break;case "tool_call_delta":if(_.arguments_delta){h+=_.arguments_delta,v+=_.arguments_delta.length;let A=Math.ceil(_.arguments_delta.length/4);if(b+=A,_.arguments_delta.trim().length>0&&this.emitEvent({type:"tool_call_delta",name:f||_.name||"unknown",argumentsDelta:_.arguments_delta}),v>1e3){let K=1-h.trim().length/v;K>.9&&(console.error(`[AgentHost] \u26A0\uFE0F Abnormal tool call: ${f} - ${(K*100).toFixed(1)}% whitespace (${v} bytes)`),this.emitLog("warn",`Model output abnormal: ${f} generating mostly whitespace content`));}if(f==="write_file"||f==="Write"||_.name==="write_file"||_.name==="Write"){let U=Math.floor(v/80),K=(v/1024).toFixed(1);this.emitEvent({type:"status",status:"tool_call",message:`\u26A1 Generating... ${K}KB (~${U} lines)`});try{let de=h.match(/"file_path"\s*:\s*"([^"]+)"/),W=h.match(/"content"\s*:\s*"/);if(de&&W){let H=de[1],ne=h.indexOf('"',W.index+9+1)+1;if(ne>0){let J=h.substring(ne),fe=-1,V=0;for(let L=0;L<J.length;L++)if(J[L]==="\\")V++;else {if(J[L]==='"'&&V%2===0){fe=L;break}V=0;}fe>0&&(J=J.substring(0,fe));let re=J.replace(/\\n/g,`
|
|
2083
|
+
`).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ue=H.split(".").pop()||"",se={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"},ae=re.split(`
|
|
2084
|
+
`),ve=ae.length<=5;re.length>2e3&&(re=re.slice(-2e3)),ve?this.emitEvent({type:"file_stream",filePath:H,content:re,language:se[ue]||ue,description:g.trim()||"Generating code...",timestamp:Date.now()}):this.emitEvent({type:"status",status:"tool_call",message:`Writing ${H} (${ae.length} lines)...`});}}}catch{p.error("MK","\u4E0D\u5B8C\u6574\u7684json \u5904\u7406");}}}break;case "tool_call_done":{if(_.name&&_.arguments)try{let A=_.arguments.trim(),O=lb(_.name,A);if(O.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&p.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${O.reason}`);let re=ab(A);if(re)process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[AgentHost] \u2705 JSON repaired successfully"),A=re;else throw new Error(`Tool arguments truncated: ${O.reason}`)}let F=A?JSON.parse(A):{};process.env.CLI_DEBUG_CONSOLE==="1"&&p.debug("TOOL",`\u2705 Tool call parsed: ${_.name}`,{argsLength:A.length});let U=Ks(_.name,F),K=this.descriptionExtractor.extractFromAssistantMessage(g,_.name);K||(K=ib(_.name,F));let de=this.commandGenerator.generateEquivalentCommand(_.name,F),W=`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,H=Date.now(),ne=this.batchDetector.detectBatch(W,_.name,U||"",F,H);this.recentToolCalls.set(_.name,{toolId:W,batchId:ne.batchId,targetPath:U,args:F});let J={targetPath:U,argsPreview:JSON.stringify(F).substring(0,200)};_.name==="search"&&F.pattern?J.pattern=F.pattern.substring(0,80):(_.name==="readfile"||_.name==="edit_file")&&F.path&&(J.file=F.path),p.info("TOOL",`\u{1F916} [AGENT] Call: ${_.name}`,J),this.emitEvent({type:"tool_call_start",name:_.name,args:F,targetPath:U,description:K,equivalentCommand:de,timestamp:H+Math.random()*.1,toolId:W,isBatch:ne.type==="batch",batchId:ne.batchId});let fe=_.name==="write_file"||_.name==="Write",V=F.file_path||F.filePath||F.path;fe&&V&&F.content&&(await this.emitFileStreamEvent(V,F.content,g.trim()||void 0),g="");}catch(A){console.error("[AgentHost] \u274C Failed to parse tool arguments for:",_.name),console.error("[AgentHost] Error:",A.message),console.error("[AgentHost] Arguments length:",_.arguments?.length||0),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.error("[AgentHost] First 200 chars:",_.arguments?.substring(0,200)||""),console.error("[AgentHost] Last 200 chars:",_.arguments?.substring(Math.max(0,(_.arguments?.length||0)-200))||""));let O=cb(_.name,_.arguments||"",A),F=O.category==="tool_truncated"?`\u274C Tool ${_.name}: content truncated during streaming`:`\u274C Tool ${_.name}: ${O.code}`;this.emitEvent({type:"status",status:"error",message:F}),this.emitEvent({type:"tool_call_start",name:_.name,args:{_raw:_.arguments?.substring(0,500)||"",_error:O.code,_errorCategory:O.category,_errorMessage:O.message,_suggestion:O.suggestion,_retryable:O.retryable},timestamp:Date.now()}),this.emitEvent({type:"tool_output",name:_.name,output:JSON.stringify(O),success:!1});}break}case "tool_output":if(_.name&&_.output!==void 0){let A=typeof _.output=="string"?_.output:JSON.stringify(_.output),O=A.length,F=_.success??!0,U=A.slice(0,db),K=A.length>db;p.info("TOOL",`\u{1F916} [AGENT] Result: ${_.name} ${F?"\u2713":"\u2717"}`,{success:F,resultLength:O,outputString:A});let de=this.recentToolCalls.get(_.name),{toolId:W,batchId:H,targetPath:ne,args:J}=de||{},fe=ne||(J&&typeof J.directory=="string"?J.directory:void 0),V=_.name==="show_tree"?`show_tree: ${fe||"."} (${O} chars)`:void 0;if(F&&fe&&this.batchDetector.recordCompletion(_.name,fe),this.emitEvent({type:"tool_call_end",name:_.name,success:F,resultLength:O,timestamp:Date.now()+Math.random()*.1,toolId:W,batchId:H,targetPath:fe,summary:V,output:U,outputTruncated:K,args:J}),_.name==="write_file"&&_.success&&J?.file_path&&J?.content){try{let re=J.file_path,ue=J.content,se=re.split(".").pop()?.toLowerCase()||"",ae={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"write_file_stream",filePath:re,content:ue,isComplete:!0,language:ae[se]||se,timestamp:Date.now()});}catch(re){p.error("TOOL","write_file_stream \u53D1\u9001\u5931\u8D25",re);}await this.handleWriteFile(J.file_path,J.content,void 0);}if(_.name==="edit_file"&&_.success&&this.sessionSync&&this.sessionEnabled)try{let re=JSON.parse(A),ue=re.metadata?.edit_info||re.edit_info,se=re.metadata?.hunks;if(p.info("TOOL","edit file\u7684\u7ED3\u679C "+re),p.info("TOOL","edit file\u7684editInfo "+ue),re.status==="success"&&ue){let ae=[];if(Array.isArray(se)&&se.length>0)for(let ee of se)ae.push({type:"file_edit_snapshot",data:{filePath:re.file_path,oldString:ee.old_string,newString:ee.new_string,startLine:ee.start_line,oldLineCount:ee.old_line_count,newLineCount:ee.new_line_count,replaceAll:!1,replacementCount:1}});else ae.push({type:"file_edit_snapshot",data:{filePath:re.file_path,oldString:ue.old_string,newString:ue.new_string,startLine:ue.start_line,oldLineCount:ue.old_line_count,newLineCount:ue.new_line_count,replaceAll:(re.metadata?.replacements||re.replacements)>1,replacementCount:re.metadata?.replacements||re.replacements}});await this.sessionSync.getSession().addItems(ae);}}catch{p.error("TOOL","session\u7684edit file \u4FDD\u5B58\u5931\u8D25 ");}if(_.name==="edit_file"&&_.success)try{let re=JSON.parse(A),ue=re.metadata?.edit_info||re.edit_info;if(re.status==="success"&&ue){let se=Array.isArray(re.metadata?.hunks)?re.metadata.hunks.map(ve=>({oldString:ve.old_string,newString:ve.new_string,startLine:ve.start_line})):void 0,ae=re.file_path.split(".").pop()?.toLowerCase()||"",ee={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"edit_file_stream",filePath:re.file_path,oldString:ue.old_string,newString:ue.new_string,startLine:ue.start_line,hunks:se,isComplete:!0,language:ee[ae]||ae,timestamp:Date.now()});}}catch{p.error("TOOL","edit file \u4FDD\u5B58\u5931\u8D25 ");}this.emitEvent({type:"tool_output",name:_.name,output:_.output,success:F});}break;case "token_usage":if(_.usage){m=_.usage.total_tokens;let A=_.usage.prompt_tokens||0,O=_.usage.completion_tokens||0,F=_.usage.prompt_tokens_details?.cached_tokens||0,U=_.usage.cache_read_input_tokens||0,K=_.usage.cache_creation_input_tokens||0,de=F||U||_.usage.cached_tokens||0,W=A+U+K+F;if(p.debug("CACHE","\u{1F525} Cache token calculation:"),p.debug("CACHE",` actualInputTokens=${A}`),p.debug("CACHE",` anthropicCacheReadTokens=${U}`),p.debug("CACHE",` anthropicCacheCreationTokens=${K}`),p.debug("CACHE",` openaiCachedTokens=${F}`),p.debug("CACHE",` fullContextInputTokens=${W}`),p.debug("CACHE",` formula: ${A} + ${U} + ${K} + ${F} = ${W}`),this.sessionTotalInputTokens+=W,this.sessionTotalOutputTokens+=O,process.env.CLI_DEBUG&&(p.debug("CONTEXT","token_usage event received:"),p.debug("CONTEXT",` actualInputTokens=${A}, actualOutputTokens=${O}`),p.debug("CONTEXT",` anthropicCacheReadTokens=${U}, openaiCachedTokens=${F}`),p.debug("CONTEXT",` anthropicCacheCreationTokens=${K}`),p.debug("CONTEXT",` fullContextInputTokens=${W}`),p.debug("CONTEXT",` sessionTotalInput=${this.sessionTotalInputTokens}, sessionTotalOutput=${this.sessionTotalOutputTokens}`),p.debug("CONTEXT",` memoryPressure initialized: ${!!this.memoryPressure}`)),this.memoryPressure){let H=this.memory.getMessagesForLLM(),ne=this.memoryPressure.estimateMessagesForDisplay(H);this.memoryPressure.recordCalibration(ne,A,U);let J=this.memoryPressure.recordActualUsage(W,O,H.length);p.debug("SNAPSHOT","\u{1F525} Snapshot values:"),p.debug("SNAPSHOT",` fullContextInputTokens (passed to recordActualUsage)=${W}`),p.debug("SNAPSHOT",` snapshot.promptTokens (returned)=${J.promptTokens}`),p.debug("SNAPSHOT",` snapshot.tokensUsed=${J.tokensUsed}`),p.debug("SNAPSHOT",` snapshot.pressure=${J.pressure}`),process.env.CLI_DEBUG&&(p.debug("CONTEXT","recordActualUsage snapshot:"),p.debug("CONTEXT",` tokensUsed=${J.tokensUsed}, promptTokens=${J.promptTokens}`),p.debug("CONTEXT",` completionTokens=${J.completionTokens}, contextWindow=${J.profile.contextWindow}`),p.debug("CONTEXT",` pressure=${J.pressure}, state=${J.state}`)),await this.handleMemorySnapshot(J);}b=0,this.emitEvent({type:"token_usage",promptTokens:W,completionTokens:O,totalTokens:W+O,cachedTokens:de>0?de:void 0,openaiCachedTokens:F>0?F:void 0,anthropicCacheReadTokens:U>0?U:void 0,anthropicCacheCreationTokens:K>0?K:void 0,sessionPromptTokens:this.sessionTotalInputTokens,sessionCompletionTokens:this.sessionTotalOutputTokens});}break;case "context_compaction":this.emitEvent({type:"context_compaction",status:_.status,originalMessages:_.originalMessages,keptMessages:_.keptMessages,droppedMessages:_.droppedMessages,compressedMessages:_.compressedMessages,originalTokens:_.originalTokens,finalTokens:_.finalTokens,budgetTokens:_.budgetTokens,useLLM:_.useLLM,timestamp:_.timestamp??Date.now()});break;case "raw_response_event":if(_.event_type==="input_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking input guardrails..."});else if(_.event_type==="output_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking output guardrails..."});else if(_.event_type==="structured_output.retry"){this.emitEvent({type:"text_complete"}),c="";let A=Array.isArray(_.data?.errors)&&_.data.errors.length>0?_.data.errors.join("; "):_.data?.message;this.emitLog("warn","Structured output validation failed",A),this.emitEvent({type:"status",status:"error",message:"Structured output invalid, retrying..."});}else if(_.event_type==="structured_output.accepted")typeof _.data?.normalized_text=="string"&&(c=_.data.normalized_text),this.emitLog("info","Structured output ready",_.data?.schema?`Schema: ${_.data.schema}`:void 0);else if(_.event_type==="error.classified"){let A=_.data;this.emitEvent({type:"error_classified",category:A.category||"INTERNAL",code:A.code||"UNKNOWN_ERROR",message:A.message||"An unknown error occurred",suggestion:A.suggestion,retryable:A.retryable??!1});}else if(_.event_type==="context_compaction"){let A=_.data;if(this.memoryPressure&&A.finalTokens!==void 0){let U=this.memoryPressure.setPromptEstimateFromMessages(this.memory.getMessagesForLLM());this.handleMemorySnapshot(U,!0);}let O=A.droppedMessages||0,F=A.compressedMessages||0;if(O>0||F>0){let U=(A.originalTokens||0)-(A.finalTokens||0),K=A.useLLM?"\u667A\u80FD\u538B\u7F29":"\u88C1\u526A";this.emitLog("info",`\u25B8 \u4E0A\u4E0B\u6587${K}`,`\u79FB\u9664 ${O} \u6761\u6D88\u606F${F>0?`\uFF0C\u538B\u7F29 ${F} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${U.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${O} messages`});}}else _.event_type==="response.completed"&&(process.env.CLI_DEBUG_CONSOLE==="1"&&p.debug("EVENTS","\u{1F4E4} Forwarding response.completed"),this.emitEvent({type:"raw_response_event",data:_.data,event_type:_.event_type}));break;case "run_done":break;case "error":p.error("AGENT",`Error: ${_.error||"Unknown error"}`),this.emitEvent({type:"error",message:_.error||"Unknown error"}),this.emitEvent({type:"status",status:"error",message:`Error: ${_.error||"Unknown error"}`});break;case "stream_retry":let P=_;this.emitEvent({type:"stream_retry",error:P.error,errorCode:P.errorCode||"STREAM_ERROR",attempt:P.attempt,maxRetries:P.maxRetries,delayMs:P.delayMs});break;case "stream_recovered":let j=_;this.emitEvent({type:"stream_recovered",attempt:j.attempt,maxRetries:j.maxRetries});break;case "plan_update":let z=_;p.info("RUNTIME_HOST","\u{1F525} Forwarding plan_update event",{hasExplanation:!!z.explanation,planSteps:z.plan?.length}),this.emitEvent({type:"plan_update",explanation:z.explanation,plan:z.plan,timestamp:z.timestamp||Date.now()});break}}process.env.CLI_DEBUG==="1"&&(p.debug("TASK","=== runner.run loop COMPLETED ==="),p.debug("TASK",` Total events: ${T}`),p.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`)),this.emitEvent({type:"text_complete"});let N=Date.now()-l,D=c;if(this.shouldInterrupt)this.emitEvent({type:"status",status:"error",message:"Task interrupted"});else if(this.emitEvent({type:"status",status:"complete",message:"Complete!"}),this.emitLog("info","Task complete",`${u} iterations, ${d} tool calls, ${m} tokens, ${(N/1e3).toFixed(2)}s`),this.sessionSync&&this.sessionEnabled&&D)try{await this.sessionSync.saveTurn({role:"user",content:i},{role:"assistant",content:D});}catch{}let $={output:D,totalTokens:m,durationMs:N,iterations:u,toolCalls:d,interrupted:this.shouldInterrupt};return this.emitEvent({type:"run_result",output:D,totalTokens:m,iterations:u,toolCalls:d,durationMs:N}),$}catch(C){if(C?.code==="ERR_CANCELED"||C?.name==="CanceledError"||C?.name==="AbortError"||C?.category==="canceled"||this.shouldInterrupt){this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:"Task interrupted"}),this.emitLog("info","Task interrupted by user");let E=Date.now()-l;return {output:c,totalTokens:m,durationMs:E,iterations:u,toolCalls:d,interrupted:true}}let w=C?.message||String(C)||"Unknown error";throw this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:`Error: ${w}`}),this.emitLog("error",`Error: ${w}`),C}finally{process.env.CLI_DEBUG&&(p.debug("TASK","=== runTask finally block START ==="),p.debug("TASK",` isRunning was: ${this.isRunning}`)),o&&this.runner.setMode(r),this.isRunning=false,this.abortController=null,this.clearInterruptPromise(),process.env.CLI_DEBUG&&p.debug("TASK","=== runTask finally block END ===");}}syncWorkspaceEnv(){this.workDir&&(process.env.NEOX_WORKDIR=this.workDir);}async listSessions(){return this.sessionManager.listSessions()}getCurrentSessionId(){return this.session?.sessionId}async getSessionInfo(){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.getSessionInfo()}async emitFileStreamEvent(e,t,n){let r=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[r]||r,a=Date.now();this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:false,language:i,description:n,timestamp:a});}async handleWriteFile(e,t,n){let r=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[r]||r,a=Date.now();try{let l=await import('fs'),c=await import('path'),u=c.isAbsolute(e)?c.resolve(e):c.resolve(this.workDir,e);if(this.sessionSync&&this.sessionEnabled)try{let d=null,m="create";l.existsSync(u)&&(m="modify",d=null);let g={type:"file_snapshot",data:{filePath:e,originalContent:d,operation:m,newContent:t}};await this.sessionSync.getSession().addItems([g]);}catch(d){console.debug("Failed to capture file snapshot",d);}this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:!0,language:i,description:n,timestamp:a}),this.emitLog("info",`\u2713 Saved ${e}`,`${t.split(`
|
|
2085
2085
|
`).length} lines written to disk`);}catch(l){this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:true,language:i,description:n,timestamp:a}),this.emitLog("error",`Error handling file write: ${l.message}`);}}async switchSession(e){let t=await this.sessionManager.getSession(e);if(!t)throw new Error(`Session ${e} not found`);return this.session=t,this.session}async createSession(e){let t=await this.sessionManager.createSession({model:e||this.model});return this.session=t,t}async saveTurn(e,t){!this.sessionSync||!this.sessionEnabled||await this.sessionSync.saveTurn({role:"user",content:e},{role:"assistant",content:t});}async undoTurns(e=1){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.undo(e)}async createCheckpoint(e){if(!this.sessionSync)throw new Error("Session is not ready");let t=await this.sessionSync.createCheckpoint(e);return this.emitEvent({type:"checkpoint",id:t}),t}async listCheckpoints(){if(!this.sessionSync)throw new Error("Session is not ready");return await this.sessionSync.getSession().getCheckpoints()}async rollbackTo(e){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.rollback(e)}async clearSession(){this.sessionSync&&await this.sessionSync.clearSession(),this.memory.clear();}async compactSession(){if(!this.sessionSync||!this.compatProfile)throw new Error("Compaction is not available");let e=this.sessionSync.getSession(),t=this.memory.getAll(),n=Hn(t),r=n.totalTokens,o=n.systemTokens,i=n.userTokens+n.assistantTokens+n.toolCallTokens+n.toolResultTokens,l=this.memoryPressure?.getSnapshot()?.profile?.contextWindow||2e5,c=r/l,u=Math.round(c*100),m=(await e.getTimeline()).filter(f=>f.item.type==="message");process.env.CLI_DEBUG==="1"&&p.debug("COMPACT","Compaction status",{llmProvider:!!this.llmProvider,totalContextTokens:r,systemPromptTokens:o,dialogTokens:i,breakdown:n,messageCount:m.length,memoryMessageCount:t.length,contextWindow:l,pressure:c});let g=`\u603B Context: ${r.toLocaleString()} tokens (${u}% \u4F7F\u7528)
|
|
2086
2086
|
\u7CFB\u7EDF\u63D0\u793A\u8BCD: ${o.toLocaleString()} tokens
|
|
2087
2087
|
\u5BF9\u8BDD\u5386\u53F2: ${i.toLocaleString()} tokens (Memory: ${t.length-1} \u6761, Session: ${m.length} \u6761)`;this.emitCompacting("\u25A0 \u538B\u7F29\u524D\u72B6\u6001",g),this.emitCompacting("\u25C7 \u538B\u7F29\u65B9\u5F0F",`\u4F7F\u7528 LLM \u667A\u80FD\u538B\u7F29
|
|
@@ -3598,7 +3598,7 @@ ${t.join(`
|
|
|
3598
3598
|
`);}finally{n&&clearTimeout(n),process.exit(e.exitCode);}}buildInstructions(){let e=this.providerSettings.protocol||"openai",t=e==="openai-responses";return process.env.CLI_DEBUG==="1"&&p.debug("PROMPT",`Protocol: ${e}, useCodexStyle: ${t}`),(n,r)=>Qo({workDir:this.workDir,language:"zh",useCodexStyle:t})}buildStaticInstructions(){let t=(this.providerSettings.protocol||"openai")==="openai-responses";return Qo({workDir:this.workDir,language:"zh",useCodexStyle:t})}displayHeader(){console.clear(),console.log();let t=Hy(process.stdout.columns).split(`
|
|
3599
3599
|
`);t.forEach((r,o)=>{if(!r.trim()){console.log();return}let i=o/Math.max(t.length-1,1),a;i<.33?a=Ie.cyan(r):i<.66?a=Ie.magenta(r):a=Ie.hex("#FF69B4")(r),console.log(a);}),console.log(),console.log(x.dim(" "+"\u2500".repeat(50))),console.log();let n=this.workDir.replace(process.env.HOME||"","~");console.log(x.dim(" Provider: ")+x.info(this.getProviderDisplayName())),console.log(x.dim(" Model: ")+x.info(this.model)),console.log(x.dim(" Dir: ")+x.info(n)),console.log(x.dim(" Tools: ")+x.info(this.tools.length.toString())),console.log(),console.log(x.dim(" Type ")+x.highlight("/help")+x.dim(" for commands \u2502 ")+x.highlight("ESC")+x.dim(" to interrupt \u2502 ")+x.error("Ctrl+C")+x.dim(" to exit")),console.log(),console.log(x.dim("\u2500".repeat(50)));}showProviderConfigurationGuide(){console.clear(),console.log(),console.log(Ie.yellow("\u2501".repeat(60))),console.log(),console.log(Ie.bold.yellow(" \u26A0\uFE0F \u6B22\u8FCE\u4F7F\u7528 Neox CLI")),console.log(),console.log(Ie.cyan(" \u{1F3AF} \u68C0\u6D4B\u5230\u60A8\u8FD8\u6CA1\u6709\u914D\u7F6E AI Provider")),console.log(Ie.dim(" \u4E3A\u4E86\u4F7F\u7528 Neox CLI\uFF0C\u60A8\u9700\u8981\u5148\u914D\u7F6E\u4E00\u4E2A AI Provider\uFF08\u5982 OpenAI\u3001Claude \u7B49\uFF09")),console.log(),console.log(Ie.bold.green(" \u{1F4A1} \u5FEB\u901F\u5F00\u59CB\uFF1A")),console.log(Ie.dim(" \u2022 \u60A8\u53EF\u4EE5\u4F7F\u7528 OpenAI\u3001Anthropic Claude\u3001Gemini \u7B49\u670D\u52A1")),console.log(Ie.dim(" \u2022 \u9700\u8981\u51C6\u5907 API Key\uFF08\u4ECE\u5BF9\u5E94\u670D\u52A1\u5546\u83B7\u53D6\uFF09")),console.log(Ie.dim(" \u2022 \u53EF\u4EE5\u4F7F\u7528\u4EE3\u7406\u5730\u5740\uFF08\u5982\u679C\u60A8\u4F7F\u7528\u7B2C\u4E09\u65B9\u4EE3\u7406\uFF09")),console.log(),console.log(Ie.bold.magenta(" \u{1F4CB} \u652F\u6301\u7684 Provider\uFF1A")),console.log(Ie.green(" OpenAI")+Ie.dim(" - GPT-4o, GPT-4, o3-mini \u7B49")),console.log(Ie.cyan(" Anthropic")+Ie.dim(" - Claude Sonnet 4.5, Claude Opus \u7B49")),console.log(Ie.yellow(" Gemini")+Ie.dim(" - Gemini 2.5 \u7CFB\u5217")),console.log(Ie.blue(" \u8C46\u5305 (Doubao)")+Ie.dim(" - \u706B\u5C71\u65B9\u821F\u6DF1\u5EA6\u601D\u8003\u6A21\u578B")),console.log(),console.log(Ie.yellow("\u2501".repeat(60))),console.log();}async runModernUI(){if(process.env.CLI_DEBUG&&(p.info("CLI","=== runModernUI() starting ==="),Ht.logStdinState("runModernUI.start")),gC()){this.showProviderConfigurationGuide(),await hC(),this.userConfig=nt(),this.providerStore=new ze(this.userConfig);let r=this.resolveProvider(void 0);this.providerSettings=r,this.providerId=r.id,this.provider=r.protocol;let o=this.providerStore.resolveModel(r.id);if(!o)throw new Error(`Provider "${r.name}" does not have any models configured. Use /model add to configure one.`);this.model=o,this.providerStore.setLastSelectedModel(r.id,this.model),this.refreshProviderSettings();}let e=this.workDir.replace(process.env.HOME||"","~");await this.initializeSession(),p.info("CLI","Using Ink UI"),this.uiController=new wl({version:Mi,provider:this.getProviderDisplayName(),model:this.model,workDir:e,commandHints:yc,getCompletions:r=>this.getCompletionSuggestions(r),memory:this.memory});let t=this.getCompressionMode(),n=this.getCompactionThreshold();if(this.uiController.setCompressionMode(t),this.uiController.setCompactionThreshold(n),this.currentRunMode==="cooperate"){let o=new Nt().getEnabledWorkerModels().map(i=>this.getModelShortName(i.model));this.uiController.updateCooperateStats({models:o.map(i=>({shortName:i,status:"idle"})),totalInputTokens:0,totalOutputTokens:0});}return this.uiController.setRunMode(this.currentRunMode),this.runtimeHost.setCompressionMode(t),this.updateContextWindowDisplay(),p.debug("CLI","Initialized context settings from userConfig",{compressionMode:t,thresholdPercent:n}),process.env.CLI_DEBUG&&(p.debug("CLI","Ink UI adapter created, starting UI..."),Ht.logStdinState("runModernUI.beforeStart")),this.uiController.start({onSubmit:async(r,o)=>{let i=o?.map(a=>({mediaType:a.mediaType,data:a.data,name:a.name||"image"}));await this.handleUserInput(r,i,"local");},onExit:()=>{process.env.CLI_DEBUG==="1"&&process.stderr.write(`
|
|
3600
3600
|
[DEBUG] onExit callback invoked
|
|
3601
|
-
`),this.exitWithCleanup({skipProcessCheck:true,exitCode:0,reason:"ui-exit"});},onInterrupt:()=>{this.isTaskRunning=false,this.runtimeHost.interrupt(),this.collabRuntime&&(this.collabRuntime.abort(),p.debug("INTERRUPT","CollabAgentRuntime aborted")),this.singleRuntime&&(this.singleRuntime.abort(),p.debug("INTERRUPT","SingleAgentRuntime aborted")),this.cooperateRuntime&&(this.cooperateRuntime.abort(),p.debug("INTERRUPT","CooperateRuntime aborted")),this.networkRuntime&&(this.networkRuntime.abort(),p.debug("INTERRUPT","NetworkRuntime aborted")),this.uiController&&(this.uiController.stopTaskTimer(),this.uiController.finalizeStreamingState?.(),this.uiController.resetStreamingState(),this.uiController.updateStatus("Ready","complete"),this.uiController.flushRenderScheduler(),this.uiController.addInfo(Ie.red("\u26A0\uFE0F Task interrupted by user"))),process.env.CLI_DEBUG==="1"&&p.debug("INTERRUPT","Task interrupted, isTaskRunning set to false"),Ht.stop();},isTaskRunning:()=>this.isTaskRunning,onToggleThinking:r=>{this.thinkingMode=r?"enabled":"disabled",fb(this.thinkingMode,this.providerControls,this.llmProvider),process.env.CLI_DEBUG==="1"&&console.log(`[THINKING] Toggled to: ${this.thinkingMode}`);}}),process.env.CLI_DEBUG&&(p.info("CLI","=== runModernUI() UI started, entering event loop ==="),Ht.logStdinState("runModernUI.afterStart")),await this.startRemoteServer(),new Promise(()=>{})}getRuntimeEventContext(){return {uiController:this.uiController,lastToolCallArgs:this.lastToolCallArgs,toolIdToName:this.toolIdToName,toolIdToArgs:this.toolIdToArgs,pushTokenStats:(e,t,n,r)=>this.pushTokenStats(e,t,n,r),getRuntimeTokens:()=>({input:this.runtimeInputTokens,output:this.runtimeOutputTokens}),setRuntimeTokens:(e,t)=>{this.runtimeInputTokens=e,this.runtimeOutputTokens=t;},getStreamingTokenCount:()=>this.streamingTokenCount,setStreamingTokenCount:e=>{this.streamingTokenCount=e;},provider:this.getProviderDisplayName(),model:this.model,sessionId:this.currentSession?.sessionId,tokenUsage:this.platformServices.tokenUsage}}async handleUserInput(e,t,n="local"){if(process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","========================================"),p.debug("INPUT","=== handleUserInput ENTRY ==="),p.debug("INPUT",` rawInput: "${e?.substring(0,50)}..."`),p.debug("INPUT",` uiController exists: ${!!this.uiController}`),p.debug("INPUT",` isTaskRunning: ${this.isTaskRunning}`),p.debug("INPUT",` stdin.isPaused: ${process.stdin.isPaused?.()}`),p.debug("INPUT",` stdin.destroyed: ${process.stdin.destroyed}`),p.debug("INPUT",` stdin.readable: ${process.stdin.readable}`),Ht.logStdinState("handleUserInput.entry")),this.isTaskRunning){if(n==="remote"){this.enqueueExecutorRun(e,n);return}if(this.currentRunMode==="network"&&this.networkRuntime?.isExecuting()){let l=e?e.trim():"";if(l){p.info("INPUT","\u{1F525} Network mode: injecting user message instead of restart",{message:l.substring(0,50)}),this.uiController&&(this.uiController.addUserMessage(l),this.uiController.addInfo("\u{1F4E8} \u6D88\u606F\u5DF2\u6CE8\u5165\u5230\u5F53\u524D\u6267\u884C\u7684 Agent",`\u6B63\u5728\u5904\u7406: "${l.substring(0,50)}${l.length>50?"...":""}"`)),this.networkRuntime.injectUserMessage(l)?p.info("INPUT","Message injected successfully"):(p.warn("INPUT","Failed to inject message, falling back to interrupt"),this.runtimeHost.interrupt(),await new Promise(u=>setTimeout(u,100)));return}}process.env.CLI_DEBUG&&p.debug("INPUT"," \u26A0\uFE0F Task already running, interrupting..."),this.runtimeHost.interrupt(),await new Promise(l=>setTimeout(l,100));}let r=e?e.trim():"";if(r=r.replace(/\[image:[^\]]+\]/g,"").trim(),!r&&t&&t.length>0&&(r="\u8BF7\u5206\u6790\u8FD9\u5F20\u56FE\u7247"),!r&&(!t||t.length===0)){process.env.CLI_DEBUG==="1"&&p.debug("INPUT","Empty input received, ignoring");return}if(r.startsWith("/")){await this.handleCommand(r);return}if(!this.uiController)return;this.sessionRequests++,this.uiController.resetStreamingState(),this.runtimeInputTokens=0,this.runtimeOutputTokens=0,this.streamingTokenCount=0,this.uiController.startTaskTimer();let o=this.pendingAttachments.length?[...this.pendingAttachments]:[];if(o.length>0&&(this.pendingAttachments=[]),t&&t.length>0){for(let l of t)try{let c;if(l.mediaType&&l.data){let u=l.mediaType,d=l.data;c=`data:${u};base64,${d}`;}else if(l.path){let u=Je.readFileSync(l.path),d=he.extname(l.path).toLowerCase();c=`data:${bc[d]||"image/png"};base64,${u.toString("base64")}`;}else throw new Error("Invalid image format: missing path or data");o.push({type:"image",data:c,path:l.path,name:l.name});}catch(c){this.uiController.addInfo(`[x] Failed to read image: ${l.name}`,c?.message);}o.some(l=>l.type==="image")&&this.uiController.addInfo(`[i] ${t.length} image(s) attached`);}let i=o.length>0||this.interactionMode!=="agent"?{mode:this.interactionMode,attachments:o.length>0?o:void 0}:void 0;process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","=== handleUserInput calling runTask ==="),Ht.logStdinState("handleUserInput.beforeRunTask"));let a=t?.map(l=>({data:"",mediaType:"image/png",path:l.path,name:l.name}));process.env.CLI_DEBUG==="1"&&p.debug("MAIN","Calling addUserMessage",{userInput:r}),this.uiController.addUserMessage(r,a),this.remoteServer&&this.remoteServer.broadcast({type:"user_input",ts:Date.now(),payload:{text:r,source:n}}),this.uiController.startSessionTimer(),this.isTaskRunning=true,this.remoteServer&&this.remoteServer.broadcast({type:"run_start",ts:Date.now(),payload:{source:n}});try{switch(this.currentRunMode){case "single":let l=await this.runOrchestratedTask(r,i);this.maybeTriggerCompletionAlerts(l);break;case "collab":await this.runCollabModeTask(r,i);break;case "cooperate":await this.runCooperateModeTask(r,i);break;case "network":await this.runNetworkModeTask(r,i);break;default:let c=await this.runOrchestratedTask(r,i);this.maybeTriggerCompletionAlerts(c);}process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","=== handleUserInput runTask completed successfully ==="),Ht.logStdinState("handleUserInput.afterRunTask.success"));}catch(l){if(l instanceof wi||l?.code==="missing_provider"){let u="No provider configured. Use /provider add to configure one.";this.uiController?(this.uiController.updateStatus(u,"error"),this.uiController.addInfo(u)):R(x.warning(` \u26A0 ${u}`));return}let c=l?.message||String(l)||"Unknown error";p.error("Agent","Task execution failed",{error:c,stack:l?.stack,userInput:r.substring(0,200)}),process.env.CLI_DEBUG==="1"&&Ht.logStdinState("handleUserInput.afterRunTask.error"),this.uiController.updateStatus(`Error: ${c}`,"error"),this.uiController.addInfo(`Error: ${c}`),this.remoteServer&&this.remoteServer.broadcast({type:"run_error",ts:Date.now(),payload:{message:c}});}finally{this.isTaskRunning=false,this.remoteServer&&this.remoteServer.broadcast({type:"run_end",ts:Date.now()}),process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","=== handleUserInput finally block ==="),p.debug("INPUT",` stdin.isPaused: ${process.stdin.isPaused?.()}`),p.debug("INPUT",` stdin.destroyed: ${process.stdin.destroyed}`),Ht.logStdinState("handleUserInput.finally")),this.memory&&process.env.INK_MEM==="1"&&this.memory.logMemoryStats(),this.uiController.stopTaskTimer(),process.env.CLI_DEBUG==="1"&&p.debug("INPUT","=== handleUserInput END - input should be available now ===");}}maybeTriggerCompletionAlerts(e){if(e.interrupted)return;let t=Di(this.userConfig);!t.soundEnabled&&!t.notifyEnabled||mv(t,{language:this.userConfig.language,summary:e});}async runInteractive(){let e=Lm();return e.debug&&p.info("CLI","Experimental features",e),e.eventLoopMonitoring&&(Nm({checkInterval:1e3,warnThreshold:5e3,criticalThreshold:1e4,autoRecover:true}).onRecovery(n=>{p.error("CLI","\u{1F6A8} Event loop critical delay detected, attempting recovery",{stats:n});}),p.info("CLI","\u2713 Event Loop monitoring enabled")),e.useInputWorker&&p.debug("CLI","InputWorker skipped in Ink UI mode (Ink has own stdin handling)"),this.runModernUI()}async handleCommand(e){let t=e.trim();if(!t)return;if(t.toLowerCase().startsWith("/thinking")){await Lv(this.getThinkingCommandContext(),t);return}let[r,...o]=t.split(/\s+/);switch(r.toLowerCase()){case "/exit":case "/quit":console.log(x.info(`
|
|
3601
|
+
`),this.exitWithCleanup({skipProcessCheck:true,exitCode:0,reason:"ui-exit"});},onInterrupt:()=>{this.isTaskRunning=false,this.runtimeHost.interrupt(),this.collabRuntime&&(this.collabRuntime.abort(),p.debug("INTERRUPT","CollabAgentRuntime aborted")),this.singleRuntime&&(this.singleRuntime.abort(),p.debug("INTERRUPT","SingleAgentRuntime aborted")),this.cooperateRuntime&&(this.cooperateRuntime.abort(),p.debug("INTERRUPT","CooperateRuntime aborted")),this.networkRuntime&&(this.networkRuntime.abort(),p.debug("INTERRUPT","NetworkRuntime aborted")),this.uiController&&(this.uiController.stopTaskTimer(),this.uiController.finalizeStreamingState?.(),this.uiController.resetStreamingState(),this.uiController.updateStatus("Ready","complete"),this.uiController.flushRenderScheduler(),this.uiController.addInfo(Ie.red("\u26A0\uFE0F Task interrupted by user"))),process.env.CLI_DEBUG==="1"&&p.debug("INTERRUPT","Task interrupted, isTaskRunning set to false"),Ht.stop();},isTaskRunning:()=>this.isTaskRunning,onToggleThinking:r=>{this.thinkingMode=r?"enabled":"disabled",fb(this.thinkingMode,this.providerControls,this.llmProvider),process.env.CLI_DEBUG==="1"&&console.log(`[THINKING] Toggled to: ${this.thinkingMode}`);}}),process.env.CLI_DEBUG&&(p.info("CLI","=== runModernUI() UI started, entering event loop ==="),Ht.logStdinState("runModernUI.afterStart")),await this.startRemoteServer(),new Promise(()=>{})}getRuntimeEventContext(){return {uiController:this.uiController,lastToolCallArgs:this.lastToolCallArgs,toolIdToName:this.toolIdToName,toolIdToArgs:this.toolIdToArgs,pushTokenStats:(e,t,n,r)=>this.pushTokenStats(e,t,n,r),getRuntimeTokens:()=>({input:this.runtimeInputTokens,output:this.runtimeOutputTokens}),setRuntimeTokens:(e,t)=>{this.runtimeInputTokens=e,this.runtimeOutputTokens=t;},getStreamingTokenCount:()=>this.streamingTokenCount,setStreamingTokenCount:e=>{this.streamingTokenCount=e;},provider:this.getProviderDisplayName(),model:this.model,sessionId:this.currentSession?.sessionId,tokenUsage:this.platformServices.tokenUsage}}async handleUserInput(e,t,n="local"){if(process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","========================================"),p.debug("INPUT","=== handleUserInput ENTRY ==="),p.debug("INPUT",` rawInput: "${e?.substring(0,50)}..."`),p.debug("INPUT",` uiController exists: ${!!this.uiController}`),p.debug("INPUT",` isTaskRunning: ${this.isTaskRunning}`),p.debug("INPUT",` stdin.isPaused: ${process.stdin.isPaused?.()}`),p.debug("INPUT",` stdin.destroyed: ${process.stdin.destroyed}`),p.debug("INPUT",` stdin.readable: ${process.stdin.readable}`),Ht.logStdinState("handleUserInput.entry")),this.isTaskRunning){if(n==="remote"){this.enqueueExecutorRun(e,n);return}if(this.currentRunMode==="network"&&this.networkRuntime?.isExecuting()){let l=e?e.trim():"";if(l){p.info("INPUT","\u{1F525} Network mode: injecting user message instead of restart",{message:l.substring(0,50)}),this.uiController&&(this.uiController.addUserMessage(l),this.uiController.addInfo("\u{1F4E8} \u6D88\u606F\u5DF2\u6CE8\u5165\u5230\u5F53\u524D\u6267\u884C\u7684 Agent",`\u6B63\u5728\u5904\u7406: "${l.substring(0,50)}${l.length>50?"...":""}"`)),this.networkRuntime.injectUserMessage(l)?p.info("INPUT","Message injected successfully"):(p.warn("INPUT","Failed to inject message, falling back to interrupt"),this.runtimeHost.interrupt(),await new Promise(u=>setTimeout(u,100)));return}}process.env.CLI_DEBUG&&p.debug("INPUT"," \u26A0\uFE0F Task already running, interrupting..."),this.runtimeHost.interrupt(),await new Promise(l=>setTimeout(l,100));}let r=e?e.trim():"";if(r=r.replace(/\[image:[^\]]+\]/g,"").trim(),!r&&t&&t.length>0&&(r="\u8BF7\u5206\u6790\u8FD9\u5F20\u56FE\u7247"),!r&&(!t||t.length===0)){process.env.CLI_DEBUG==="1"&&p.debug("INPUT","Empty input received, ignoring");return}if(r.startsWith("/")){await this.handleCommand(r);return}if(!this.uiController)return;this.sessionRequests++,this.uiController.resetStreamingState(),this.runtimeInputTokens=0,this.runtimeOutputTokens=0,this.streamingTokenCount=0,this.uiController.startTaskTimer();let o=this.pendingAttachments.length?[...this.pendingAttachments]:[];if(o.length>0&&(this.pendingAttachments=[]),t&&t.length>0){for(let l of t)try{let c;if(l.mediaType&&l.data){let u=l.mediaType,d=l.data;c=`data:${u};base64,${d}`;}else if(l.path){let u=Je.readFileSync(l.path),d=he.extname(l.path).toLowerCase();c=`data:${bc[d]||"image/png"};base64,${u.toString("base64")}`;}else throw new Error("Invalid image format: missing path or data");o.push({type:"image",data:c,path:l.path,name:l.name});}catch(c){this.uiController.addInfo(`[x] Failed to read image: ${l.name}`,c?.message);}o.some(l=>l.type==="image")&&this.uiController.addInfo(`[i] ${t.length} image(s) attached`);}let i=o.length>0||this.interactionMode!=="agent"?{mode:this.interactionMode,attachments:o.length>0?o:void 0}:void 0;process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","=== handleUserInput calling runTask ==="),Ht.logStdinState("handleUserInput.beforeRunTask"));let a=t?.map(l=>({data:"",mediaType:"image/png",path:l.path,name:l.name}));process.env.CLI_DEBUG==="1"&&p.debug("MAIN","Calling addUserMessage",{userInput:r}),this.uiController.addUserMessage(r,a),this.remoteServer&&this.remoteServer.broadcast({type:"user_input",ts:Date.now(),payload:{text:r,source:n}}),this.uiController.startSessionTimer(),this.isTaskRunning=true,this.remoteServer&&this.remoteServer.broadcast({type:"run_start",ts:Date.now(),payload:{source:n}});try{switch(this.currentRunMode){case "single":let l=await this.runOrchestratedTask(r,i);this.maybeTriggerCompletionAlerts(l);break;case "collab":await this.runCollabModeTask(r,i);break;case "cooperate":await this.runCooperateModeTask(r,i);break;case "network":await this.runNetworkModeTask(r,i);break;default:let c=await this.runOrchestratedTask(r,i);this.maybeTriggerCompletionAlerts(c);}process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","=== handleUserInput runTask completed successfully ==="),Ht.logStdinState("handleUserInput.afterRunTask.success"));}catch(l){if(l instanceof wi||l?.code==="missing_provider"){let u="No provider configured. Use /provider add to configure one.";this.uiController?(this.uiController.updateStatus(u,"error"),this.uiController.addInfo(u)):R(x.warning(` \u26A0 ${u}`));return}let c=l?.message||String(l)||"Unknown error";p.error("Agent","Task execution failed",{error:c,stack:l?.stack,userInput:r.substring(0,200)}),process.env.CLI_DEBUG==="1"&&Ht.logStdinState("handleUserInput.afterRunTask.error"),this.uiController.updateStatus(`Error: ${c}`,"error"),this.uiController.addInfo(`Error: ${c}`),this.remoteServer&&this.remoteServer.broadcast({type:"run_error",ts:Date.now(),payload:{message:c}});}finally{this.isTaskRunning=false,this.remoteServer&&this.remoteServer.broadcast({type:"run_end",ts:Date.now()}),process.env.CLI_DEBUG==="1"&&(p.debug("INPUT","=== handleUserInput finally block ==="),p.debug("INPUT",` stdin.isPaused: ${process.stdin.isPaused?.()}`),p.debug("INPUT",` stdin.destroyed: ${process.stdin.destroyed}`),Ht.logStdinState("handleUserInput.finally")),this.memory&&process.env.INK_MEM==="1"&&this.memory.logMemoryStats(),this.uiController.stopTaskTimer(),process.env.CLI_DEBUG==="1"&&p.debug("INPUT","=== handleUserInput END - input should be available now ===");}}maybeTriggerCompletionAlerts(e){if(e.interrupted)return;let t=Di(this.userConfig);!t.soundEnabled&&!t.notifyEnabled||mv(t,{language:this.userConfig.language,summary:e});}async runInteractive(){let e=Lm();return e.debug&&p.info("CLI","Experimental features",e),e.eventLoopMonitoring&&(Nm({checkInterval:1e3,warnThreshold:5e3,criticalThreshold:1e4,autoRecover:true}).onRecovery(n=>{p.error("CLI","\u{1F6A8} Event loop critical delay detected, attempting recovery",{stats:n});}),p.info("CLI","\u2713 Event Loop monitoring enabled")),e.useInputWorker&&p.debug("CLI","InputWorker skipped in Ink UI mode (Ink has own stdin handling)"),this.runModernUI()}async handleCommand(e){let t=e.trim();if(!t)return;if(t.toLowerCase().startsWith("/thinking")){await Lv(this.getThinkingCommandContext(),t);return}let[r,...o]=t.split(/\s+/);switch(r.toLowerCase()){case "/exit":case "/quit":case "exit":case "quit":console.log(x.info(`
|
|
3602
3602
|
\u{1F44B} Goodbye!`)),this.exitWithCleanup({skipProcessCheck:false,exitCode:0,reason:"command"});break;case "/help":if(this.uiController)e:for(;;)try{let a=await this.uiController.promptSelect({message:"Select action",choices:hv(),initialValue:this.helpMenuLastSelection});if(a===null||a==="exit")break e;switch(a&&(this.helpMenuLastSelection=a),await new Promise(l=>setTimeout(l,50)),a){case "provider":await this.handleCommand("/provider");break;case "model":await this.handleCommand("/model");break;case "session":await this.handleCommand("/sessions");break;case "workspace":await this.handleCommand("/workspace");break;case "mode":await this.handleCommand("/mode");break;case "collab":await this.handleCommand("/collab");break;case "sandbox":await this.handleCommand("/sandbox");break;case "thinking":await this.handleCommand("/thinking");break;case "approval":await this.handleCommand("/approval");break;case "notify":await this.handleCommand("/notify");break;case "index":await this.handleCommand("/index");break;case "context":await this.handleCommand("/context");break;case "memory":await this.handleCommand("/memory");break;case "remote":await this.handleCommand("/remote");break;case "statistic":await this.handleCommand("/statistic");break;case "help-text":let l=[];xc(c=>{l.push(c);}),this.logInfo("Neox CLI Help",l.join(`
|
|
3603
3603
|
`));break}break e}catch(a){if(a.message!=="cancelled"&&a.message!=="User cancelled"){let l=[];xc(c=>l.push(c)),this.logInfo("Neox CLI Help",l.join(`
|
|
3604
3604
|
`));}break e}else xc();break;case "/schema-example":await uv(this.workDir,o[0]);break;case "/mode":{let a=(o[0]||"").toLowerCase();if(a&&a!=="status"){if(a!=="agent"&&a!=="ask"){this.logInfo("\u65E0\u6548\u7684\u6A21\u5F0F","\u53EF\u7528\u6A21\u5F0F: agent, ask");break}if(this.interactionMode===a){this.logInfo("\u6A21\u5F0F\u672A\u53D8\u5316",`\u4ECD\u4E3A ${a}`);break}this.interactionMode=a,this.logInfo("\u4EA4\u4E92\u6A21\u5F0F\u5DF2\u66F4\u65B0",a==="ask"?"\u5C06\u4EE5\u66F4\u5BF9\u8BDD\u7684\u65B9\u5F0F\u56DE\u7B54\uFF0C\u5E76\u51CF\u5C11\u5DE5\u5177\u8C03\u7528\u3002":"\u6062\u590D\u9ED8\u8BA4\u7684 Agent \u6A21\u5F0F\uFF0C\u53EF\u81EA\u52A8\u8C03\u7528\u5DE5\u5177\u3002");break}try{let l=await this.promptSelect("Select mode",[{label:"Agent",value:"agent",description:"\u667A\u80FD\u4F53\u81EA\u52A8\u4F7F\u7528\u5DE5\u5177\uFF0C\u9002\u5408\u4EE3\u7801\u4EFB\u52A1"},{label:"Ask",value:"ask",description:"\u4EC5\u56DE\u7B54\u95EE\u9898\uFF0C\u5C3D\u91CF\u907F\u514D\u5DE5\u5177\u8C03\u7528"}],this.interactionMode);this.interactionMode!==l?(this.interactionMode=l,this.logInfo("\u4EA4\u4E92\u6A21\u5F0F\u5DF2\u66F4\u65B0",l==="ask"?"\u5C06\u4EE5\u66F4\u5BF9\u8BDD\u7684\u65B9\u5F0F\u56DE\u7B54\uFF0C\u5E76\u51CF\u5C11\u5DE5\u5177\u8C03\u7528\u3002":"\u6062\u590D\u9ED8\u8BA4\u7684 Agent \u6A21\u5F0F\uFF0C\u53EF\u81EA\u52A8\u8C03\u7528\u5DE5\u5177\u3002")):this.logInfo("\u6A21\u5F0F",`\u5F53\u524D\u6A21\u5F0F: ${l}`);}catch(l){l.message!=="cancelled"&&this.logInfo("Mode selection failed",l.message);}break}case "/collab":case "/collaboration":{let a=(o[0]||"").toLowerCase();if(a==="mode"){let l=(o[1]||"").toLowerCase();if(xn.isValidMode(l)){this.setRunMode(l);let c=xn.getModeDescription(l),u={single:"\u{1F464}",collab:"\u{1F91D}",cooperate:"\u{1F527}",network:"\u{1F310}"};this.logInfo(`${u[l]} \u5DF2\u5207\u6362\u5230 ${l} \u6A21\u5F0F`,c);break}try{let c=await this.promptSelect("\u9009\u62E9\u8FD0\u884C\u6A21\u5F0F",[{label:"\u{1F464} \u5355 Agent \u6A21\u5F0F",value:"single",description:"\u65E5\u5E38\u5F00\u53D1\uFF0C\u5FEB\u901F\u8FED\u4EE3\uFF0C\u6700\u4F4E\u5F00\u9500"},{label:"\u{1F91D} \u534F\u4F5C\u6A21\u5F0F",value:"collab",description:"spawn_agent \u5DE5\u5177\uFF0C\u52A8\u6001\u59D4\u6D3E"},{label:"\u{1F527} \u5408\u4F5C\u6A21\u5F0F",value:"cooperate",description:"\u9759\u6001 DAG + CCB \u8BC4\u5BA1\u6D41\u7A0B"},{label:"\u{1F310} \u81EA\u7EC4\u7EC7\u7F51\u7EDC",value:"network",description:"Agent \u81EA\u4E3B\u7EC4\u7F51\uFF0C\u52A8\u6001\u534F\u5546 (\u5F00\u53D1\u4E2D)"}],this.getCurrentRunMode());if(xn.isValidMode(c)){this.setRunMode(c);let u={single:"\u{1F464}",collab:"\u{1F91D}",cooperate:"\u{1F527}",network:"\u{1F310}"},d=xn.getModeDescription(c);this.logInfo(`${u[c]} \u5DF2\u5207\u6362\u5230 ${c} \u6A21\u5F0F`,d);}}catch(c){c.message!=="cancelled"&&this.logInfo("\u6A21\u5F0F\u9009\u62E9\u5931\u8D25",c.message);}break}if(xn.isValidMode(a)){this.setRunMode(a);let l=xn.getModeDescription(a),c={single:"\u{1F464}",collab:"\u{1F91D}",cooperate:"\u{1F527}",network:"\u{1F310}"};this.logInfo(`${c[a]} \u5DF2\u5207\u6362\u5230 ${a} \u6A21\u5F0F`,l);break}if(a==="on"||a==="enable"||a==="1"){this.setRunMode("collab"),this.logInfo("\u{1F91D} \u534F\u4F5C\u6A21\u5F0F\u5DF2\u5F00\u542F","spawn_agent \u5DE5\u5177\u53EF\u7528\uFF0C\u9002\u5408\u9700\u8981\u5E76\u884C\u6267\u884C\u7684\u4EFB\u52A1");break}if(a==="off"||a==="disable"||a==="0"){this.setRunMode("single"),this.logInfo("\u{1F464} \u5355 Agent \u6A21\u5F0F","\u6700\u5FEB\u901F\u7B80\u6D01\u7684\u6267\u884C\u65B9\u5F0F");break}if(a==="status"){let l=this.getCurrentRunMode(),c={single:"\u{1F464}",collab:"\u{1F91D}",cooperate:"\u{1F527}",network:"\u{1F310}"},u=xn.getModeDescription(l);this.logInfo(`\u5F53\u524D\u8FD0\u884C\u6A21\u5F0F: ${c[l]} ${l}`,u);break}await tC(this.getCollabCommandContext(),a||void 0);break}case "/attach":{if(!o.length){this.logInfo("\u7528\u6CD5","/attach <\u56FE\u7247\u8DEF\u5F84\u6216 URL>");break}if(o[0].toLowerCase()==="clear"){this.clearPendingAttachments();break}await this.addPendingAttachment(o.join(" "));break}case "/attachments":{if(!o.length||o[0].toLowerCase()==="list"){this.listPendingAttachments();break}if(o[0].toLowerCase()==="clear"){this.clearPendingAttachments();break}if(o[0].toLowerCase()==="remove"){let a=parseInt(o[1],10);if(isNaN(a)||a<1){this.logInfo("\u7528\u6CD5","/attachments remove <\u7F16\u53F7>");break}this.removePendingAttachment(a-1);break}this.logInfo("\u7528\u6CD5","/attachments [list|clear|remove <\u7F16\u53F7>]");break}case "/approval":await $v(this.getConfigCommandContext(),o[0]);break;case "/notify":await Bv(this.getNotifyCommandContext(),o[0]);break;case "/remote":await Jv(this.getRemoteCommandContext(),o[0]);break;case "/supervisor":await Qv(this.getSupervisorCommandContext(),o[0]);break;case "/provider":{let a=(o[0]||"").toLowerCase(),l=this.getProviderCommandContext();switch(a){case "":await bm(l);break;case "list":Li(l);break;case "add":await Sc(l);break;case "edit":case "update":await _c(l,o[1]);break;case "remove":case "delete":await fm(l,o[1]);break;case "use":await kc(l,o[1]);break;case "default":await ym(l,o[1]);break;default:await kc(l,a);break}break}case "/sandbox":{let a=(o[0]||"").toLowerCase(),l=Br();if(a==="on"||a==="enable"){this.runtimeHost.setSandboxMode(true),this.logInfo("Sandbox enabled","\u6C99\u7BB1\u6A21\u5F0F\u5DF2\u542F\u7528\uFF0C\u4EC5\u5141\u8BB8\u5B89\u5168\u547D\u4EE4");break}if(a==="off"||a==="disable"){this.runtimeHost.setSandboxMode(false),this.logInfo("Sandbox disabled","\u5168\u529F\u80FD\u6A21\u5F0F\uFF0C\u6240\u6709\u547D\u4EE4\u53EF\u6267\u884C");break}try{let u=await this.promptSelect("Sandbox mode",[{label:"Off (Full mode)",value:"off",description:"\u6240\u6709 shell \u547D\u4EE4\u90FD\u53EF\u4EE5\u6267\u884C"},{label:"On (Restricted)",value:"on",description:"\u4EC5\u5141\u8BB8 ls, pwd, cat, grep \u7B49\u5B89\u5168\u547D\u4EE4"}],l?"on":"off")==="on";u!==l?(this.runtimeHost.setSandboxMode(u),this.logInfo(u?"Sandbox enabled":"Sandbox disabled",u?"\u6C99\u7BB1\u6A21\u5F0F\u5DF2\u542F\u7528\uFF0C\u4EC5\u5141\u8BB8\u5B89\u5168\u547D\u4EE4":"\u5168\u529F\u80FD\u6A21\u5F0F\uFF0C\u6240\u6709\u547D\u4EE4\u53EF\u6267\u884C")):this.logInfo("Sandbox",`\u5F53\u524D\u72B6\u6001: ${u?"\u5DF2\u542F\u7528":"\u5DF2\u7981\u7528"}`);}catch(c){c.message!=="cancelled"&&this.logInfo("Sandbox selection failed",c.message);}break}case "/model":{let a=(o[0]||"").toLowerCase(),l=o.slice(1),c=this.getProviderCommandContext();switch(a){case "":await Dv(c);break;case "list":await Mv(c,l[0]);break;case "add":await Ec(c,l[0]);break;case "remove":case "delete":await Ac(c,l[0]);break;case "default":await Rv(c,l[0]);break;case "use":await Cm(c,l[0],l[1]);break;case "config":case "configure":await Nv(c,l[0]);break;default:await Cm(c,void 0,a);break}break}case "/clear":this.memory.clear(),this.logInfo("Conversation history cleared","\u5BF9\u8BDD\u5386\u53F2\u5DF2\u6E05\u7A7A");break;case "/config-clear":case "/config-reset":await Ov(this.getConfigCommandContext());break;case "/index":case "/index-build":case "/index-status":await Uv(this.getIndexCommandContext(),o[0]);break;case "/context":await $n(this.getContextCommandContext(),o[0]);break;case "/memory":await Hv(this.getMemoryCommandContext(),o[0]);break;case "/workspace":case "/workdir":await this.handleWorkspaceCommand(o);break;case "/statistic":case "/statistics":await oo(this.getStatisticCommandContext(),o[0]);break;case "/stats":{let a=this.workDir.replace(process.env.HOME||"","~"),l=await this.runtimeHost.getSessionInfo().catch(()=>null),c=d=>!d||d.length<8?"***":`${d.slice(0,4)}...${d.slice(-4)}`,u=["",x.highlight(" \u{1F4CA} \u4F1A\u8BDD\u7EDF\u8BA1\u4FE1\u606F"),"",x.dim(" \u57FA\u672C\u4FE1\u606F:"),x.dim(" Directory: ")+x.info(a),x.dim(" Provider: ")+x.info(this.getProviderDisplayName()),x.dim(" Model: ")+x.info(this.model)];if(this.providerSettings&&(u.push(""),u.push(x.dim(" Provider \u914D\u7F6E:")),this.providerSettings.baseUrl&&u.push(x.dim(" API URL: ")+x.info(this.providerSettings.baseUrl)),this.providerSettings.apiKey&&u.push(x.dim(" API Key: ")+x.dim(c(this.providerSettings.apiKey))),this.providerSettings.maxTokens&&u.push(x.dim(" Max Out: ")+x.info(this.providerSettings.maxTokens.toString()+" tokens"))),u.push(""),u.push(x.dim(" \u4F1A\u8BDD\u72B6\u6001:")),u.push(x.dim(" Messages: ")+x.info(this.memory.length.toString())),u.push(x.dim(" Tools: ")+x.info(this.tools.length.toString())),u.push(x.dim(" Requests: ")+x.info(this.sessionRequests.toString())),l&&(u.push(x.dim(" Session: ")+x.info(l.sessionId)),u.push(x.dim(" Turns: ")+x.info(l.turnCount.toString()))),u.push(""),u.push(x.dim(" \u8FD0\u884C\u6A21\u5F0F:")),u.push(x.dim(" Mode: ")+x.info(this.interactionMode==="agent"?"Agent (\u5DE5\u5177\u8C03\u7528)":"Ask (\u7EAF\u5BF9\u8BDD)")),u.push(x.dim(" Sandbox: ")+x.info(Br()?"On (\u5B89\u5168\u6A21\u5F0F)":"Off")),u.push(x.dim(" Approval: ")+x.info(this.userConfig.agentApprovalMode||this.userConfig.approvalMode||"auto")),this.thinkingMode!=="disabled"&&u.push(x.dim(" Thinking: ")+x.success("On (\u6DF1\u5EA6\u601D\u8003)")),u.push(""),this.uiController)if(typeof this.uiController.setCommandOutputLines=="function")this.uiController.setCommandOutputLines(u);else for(let d of u)this.uiController.printCommandOutput(d);else for(let d of u)R(d);break}case "/sessions":await Tc(this.getCommandContext());break;case "/session":o[0]?await yv(this.getCommandContext(),o[0]):await Tc(this.getCommandContext());break;case "/session-new":await bv(this.getCommandContext(),this.model);break;case "/session-info":await vv(this.getCommandContext());break;case "/undo":await Cv(this.getCommandContext(),o[0]);break;case "/checkpoint":await xv(this.getCommandContext(),o.join(" "));break;case "/checkpoints":await Tv(this.getCommandContext());break;case "/rollback":await wv(this.getCommandContext(),o[0]);break;case "/session-clear":await kv(this.getCommandContext());break;case "/session-export":await Sv(this.getCommandContext(),o[0]);break;case "/compact":this.autoCompactionInProgress=await _v(this.getCommandContext());break;case "/processes":case "/ps":await Iv(o[0]);break;case "/kill":await Ev(o[0]);break;default:this.logInfo("Unknown command",`Command: ${r}
|