@iflow-ai/iflow-cli-sdk 0.1.9-beta.2 ā 0.2.0-beta.0
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/CHANGELOG.md +63 -0
- package/README.md +264 -219
- package/README_CN.md +190 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +359 -92
- package/dist/index.mjs +1 -1
- package/package.json +6 -2
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"fs";import t from"fs";import*as n from"path";import s from"path";import o from"ws";import*as i from"fs/promises";import*as r from"os";import a from"os";import*as c from"net";import*as l from"child_process";import d from"child_process";import u from"assert";import p from"events";import h from"buffer";import f from"stream";import m from"util";class g extends Error{constructor(e,t){super(e),this.name="IFlowError",this.details=t||{}}}class w extends g{constructor(e,t){super(e,t),this.name="TimeoutError"}}class y extends g{constructor(e,t){super(e,{rawData:t}),this.name="JSONDecodeError",this.rawData=t}}class S extends g{constructor(e,t){super(e,t),this.name="IFlowNotInstalledError"}}class E extends g{constructor(e,t){super(e,t),this.name="IFlowProcessError"}}class I extends g{constructor(e,t){super(e,t),this.name="PortNotAvailableError"}}class T extends g{constructor(e,t){super(e,t),this.name="ConnectionError"}}class x extends g{constructor(e,t){super(e,t),this.name="TransportError"}}class v extends g{constructor(e,t){super(e,t),this.name="PermissionError"}}class b extends g{constructor(e,t){super(e,t),this.name="ValidationError"}}class A extends g{constructor(e,t){super(e,t),this.name="ProtocolError"}}class O extends g{constructor(e,t){super(e,t),this.name="AuthenticationError"}}var P,_,C,R,$,N,L,F,M,k,G,U,D;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(P||(P={})),function(e){e.AUTO="auto",e.MANUAL="manual",e.SELECTIVE="selective"}(_||(_={})),function(e){e.DEFAULT="default",e.AUTO_EDIT="autoEdit",e.YOLO="yolo",e.PLAN="plan"}(C||(C={})),function(e){e.PRE_TOOL_USE="PreToolUse",e.POST_TOOL_USE="PostToolUse",e.STOP="Stop",e.SUBAGENT_STOP="SubagentStop",e.SET_UP_ENVIRONMENT="SetUpEnvironment"}(R||(R={})),function(e){e.HIGH="high",e.MEDIUM="medium",e.LOW="low"}($||($={})),function(e){e.PENDING="pending",e.IN_PROGRESS="in_progress",e.COMPLETED="completed"}(N||(N={})),function(e){e.END_TURN="end_turn",e.MAX_TOKENS="max_tokens",e.REFUSAL="refusal",e.CANCELLED="cancelled"}(L||(L={})),function(e){e.PENDING="pending",e.IN_PROGRESS="in_progress",e.COMPLETED="completed",e.FAILED="failed"}(F||(F={})),function(e){e.DIFF="diff",e.MARKDOWN="markdown"}(M||(M={})),function(e){e.EDIT="edit",e.EXECUTE="execute",e.MCP="mcp",e.FETCH="fetch",e.OTHER="other"}(k||(k={})),function(e){e.ALLOW="allow",e.ALWAYS_ALLOW="alwaysAllow",e.ALWAYS_ALLOW_TOOL="alwaysAllowTool",e.ALWAYS_ALLOW_MCP_SERVER="alwaysAllowMcpServer",e.REJECT="reject"}(G||(G={})),function(e){e.URL="url",e.EMOJI="emoji"}(U||(U={})),function(e){e.PLAN="plan",e.USER="user",e.ASSISTANT="assistant",e.TOOL_CALL="tool_call",e.ERROR="error",e.TASK_FINISH="task_finish"}(D||(D={}));const j="2.0";var H,W,B;function K(e){if(e instanceof Error){const t=e,n=t.details?.data?.details;return n?`${e.message}\n${n}`:e.message}return e?String(e):"unknown error"}!function(e){e.INITIALIZE="initialize",e.AUTHENTICATE="authenticate",e.SESSION_NEW="session/new",e.SESSION_LOAD="session/load",e.SESSION_PROMPT="session/prompt",e.SESSION_CANCEL="session/cancel"}(H||(H={})),function(e){e.SESSION_UPDATE="session/update",e.SESSION_REQUEST_PERMISSION="session/request_permission",e.FS_READ_TEXT_FILE="fs/read_text_file",e.FS_WRITE_TEXT_FILE="fs/write_text_file",e.PUSH_TOOL_CALL="pushToolCall",e.UPDATE_TOOL_CALL="updateToolCall",e.NOTIFY_TASK_FINISH="notifyTaskFinish"}(W||(W={})),function(e){e.PLAN="plan",e.TOOL_CALL="tool_call",e.TOOL_CALL_UPDATE="tool_call_update",e.USER_MESSAGE_CHUNK="user_message_chunk",e.AGENT_MESSAGE_CHUNK="agent_message_chunk",e.AGENT_THOUGHT_CHUNK="agent_thought_chunk"}(B||(B={}));class z{constructor(e={}){const t=e.level||"INFO";this.level=P[t]}debug(e){this.log(P.DEBUG,e)}info(e){this.log(P.INFO,e)}warn(e){this.log(P.WARN,e)}error(e,t){this.log(P.ERROR,e,t)}log(e,t,n){if(e<this.level)return;const s=`[${(new Date).toLocaleString("sv-SE").replace("T"," ")}] ${P[e]}: ${t}${n?`\n${n.stack}`:""}`;switch(e){case P.DEBUG:console.debug(s);break;case P.INFO:console.info(s);break;case P.WARN:console.warn(s);break;case P.ERROR:console.error(s)}}}const q=new z;function Q(e){return!!e&&"id"in e&&"result"in e&&null!=e.result}function X(e){return!!e&&"id"in e&&"error"in e&&null!=e.error}function V(e){return!!e&&"method"in e&&!("result"in e)&&!("error"in e)}class J{constructor(e){this.requestId=0,this.initialized=!1,this.authenticated=!1,this.logger=e.logger||q,this.transport=e.transport,this.fileHandler=e.fileHandler,this.permissionMode=e.permissionMode||_.AUTO,this.autoApproveTypes=e.autoApproveTypes||["read","fetch","list"]}nextRequestId(){return++this.requestId}checkAuthenticated(){if(!this.initialized)throw new A("Protocol not initialized. Call initialize() first.");if(!this.authenticated)throw new A("Not authenticated. Call authenticate() first.")}async sendResult(e,t){const n={jsonrpc:j,id:e,result:t};await this.transport.send(n)}async sendError(e,t,n){const s={jsonrpc:j,id:e,error:{code:t,message:n}};await this.transport.send(s)}async waitForReadySignal(){for await(const e of this.transport.receive()){const t=e.trim();if("//ready"===t){this.logger.info("Received //ready signal");break}t.startsWith("//")&&this.logger.debug(`Control message: ${t}`)}}async waitForMessageResponse(e,t,n){const{timeout:s,timeoutMsg:o=`Timeout after ${s} seconds`}=n||{},i=Date.now();for await(const n of this.transport.receive()){if(n.trim().startsWith("//")){this.logger.debug(`Control message: ${n.trim()}`);continue}let r;try{r=JSON.parse(n.trim())}catch(e){this.logger.error(`Failed to parse response: ${K(e)}`);continue}if(r.id===e){const e=t(r);if(void 0!==e)return e}if(s&&s>0&&Date.now()-i>s)throw new w(o)}}async initialize(e={}){if(this.initialized)return this.logger.warn("Protocol already initialized"),{protocolVersion:1,isAuthenticated:this.authenticated};this.logger.info("Waiting for //ready signal..."),await this.waitForReadySignal();const t=this.nextRequestId(),n={jsonrpc:j,id:t,method:H.INITIALIZE,params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}},...e}};await this.transport.send(n),this.logger.info("Sent initialize request");const s=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new A(`Initialize failed: ${e.error?.message}`,e.error);const t=e.result||{};return this.initialized=!0,this.authenticated=t.isAuthenticated||!1,this.logger.info(`Initialized with protocol version: ${t.protocolVersion}, authenticated: ${this.authenticated}`),t},{timeout:1e4,timeoutMsg:"Initialize timeout after 10 seconds"});if(s)return s;throw new A("Connection closed during initialization")}async authenticate(e={}){const t=e.methodId||"iflow";if(this.authenticated)return void this.logger.warn("Already authenticated");const n=this.nextRequestId(),s={jsonrpc:j,id:n,method:H.AUTHENTICATE,params:{...e,methodId:t}};await this.transport.send(s),this.logger.info(`Sent authenticate request with method: ${s.params.methodId}`);if(!await this.waitForMessageResponse(n,e=>{if("error"in e)throw new O(`Authentication failed: ${e.error?.message}`,e.error);const n=e.result||{};return n.methodId===t?(this.authenticated=!0,this.logger.info(`Authentication successful with method: ${n.methodId}`),!0):(this.authenticated=!0,this.logger.warn(`Unexpected methodId in response: ${n.methodId} (expected ${t})`),!0)},{timeout:1e4,timeoutMsg:"Authentication timeout after 10 seconds"}))throw new O("Connection closed during authentication")}async createSession(e={}){this.checkAuthenticated();const t=this.nextRequestId(),n={jsonrpc:j,id:t,method:H.SESSION_NEW,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(n),this.logger.info(`Sent session/new request with cwd: ${e.cwd}`);const s=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new A(`session/new failed: ${e.error?.message}`,e.error);const t=e.result||{};if(t.sessionId)return this.logger.info(`Created session: ${t.sessionId}`),t.sessionId;throw new A(`Invalid session/new response: ${JSON.stringify(t)}`)},{timeout:1e4,timeoutMsg:"Session creation timeout after 10 seconds"});if(s)return s;throw new A("Connection closed while waiting for session/new response")}async loadSession(e){this.checkAuthenticated();const t=this.nextRequestId(),n={jsonrpc:j,id:t,method:H.SESSION_LOAD,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(n),this.logger.info(`Sent session/load request for session: ${e.sessionId}`);if(!await this.waitForMessageResponse(t,t=>{if("error"in t){if(-32601===t.error.code)throw new A("session/load is not supported by the current iFlow version. Use session/new to create a new session instead.",t.error);throw new A(`session/load failed: ${t.error?.message}`,t.error)}return this.logger.info(`Session loaded successfully: ${e.sessionId}`),!0},{timeout:1e4,timeoutMsg:"Session load timeout after 10 seconds"}))throw new A("Connection closed while waiting for session/load response")}async sendPrompt(e){this.checkAuthenticated();const t=this.nextRequestId(),n={jsonrpc:j,id:t,method:H.SESSION_PROMPT,params:e};return await this.transport.send(n),this.logger.info(`Sent prompt with ${e.prompt.length} content blocks`),t}async cancelSession(e){this.checkAuthenticated();const t=this.nextRequestId(),n={jsonrpc:j,id:t,method:H.SESSION_CANCEL,params:e};await this.transport.send(n),this.logger.info("Sent session/cancel request")}async*handleMessages(){for await(const e of this.transport.receive()){if(e.trim().startsWith("//")){this.logger.debug(`Control message: ${e.trim()}`);continue}let t;try{t=JSON.parse(e.trim())}catch(t){throw this.logger.error(`Failed to parse message: ${K(t)}`),new y("Invalid JSON received",e)}V(t)?yield await this.handleClientMessage(t):Q(t)?yield{type:"response",id:t.id,result:t.result}:X(t)&&(yield{type:"error",code:t.error.code,error:t.error.message})}}async handleClientMessage(e){const{method:t}=e;switch(t){case W.FS_READ_TEXT_FILE:return await this.handleReadTextFile(e);case W.FS_WRITE_TEXT_FILE:return await this.handleWriteTextFile(e);case W.SESSION_UPDATE:return await this.handleSessionUpdate(e);case W.SESSION_REQUEST_PERMISSION:return await this.handleRequestPermission(e);case W.PUSH_TOOL_CALL:return await this.handlePushToolCall(e);case W.UPDATE_TOOL_CALL:return await this.handleUpdateToolCall(e);case W.NOTIFY_TASK_FINISH:return await this.handleNotifyTaskFinish(e);default:return await this.handleUnknownMessage(e)}}async handleReadTextFile(e){const{id:t,method:n,params:s}=e,{path:o,limit:i,line:r}=s||{};let a;if(this.logger.info(`fs/read_text_file request for: ${o}`),!this.fileHandler){const e="File system access not configured";return void 0!==t&&await this.sendError(t,-32603,e),{type:"error",code:-32603,error:e,method:n}}try{a=await this.fileHandler.readFile(o,r,i)}catch(e){const s=K(e);return this.logger.error(`Error reading file ${o}: ${s}`),void 0!==t&&await this.sendError(t,-32603,s),{type:"error",code:-32603,error:s,method:n}}return void 0!==t&&await this.sendResult(t,{content:a}),{type:"file_read",path:o,content:a}}async handleWriteTextFile(e){const{id:t,method:n,params:s}=e,{path:o,content:i}=s||{};if(this.logger.info(`fs/write_text_file request for: ${o}`),!this.fileHandler){const e="File system access not configured";return void 0!==t&&await this.sendError(t,-32603,e),{type:"error",code:-32603,error:e,method:n}}try{await this.fileHandler.writeFile(o,i)}catch(e){const s=K(e);return this.logger.error(`Error writing file ${o}: ${s}`),void 0!==t&&await this.sendError(t,-32603,s),{type:"error",code:-32603,error:s,method:n}}return void 0!==t&&await this.sendResult(t,{success:!0}),{type:"file_write",path:o,content:i}}async handleSessionUpdate(e){const{params:t}=e,{sessionId:n,update:s}=t;return{type:"session_update",sessionId:n,updateData:s}}async handleRequestPermission(e){const{id:t,params:n}=e,s=n.toolCall||{},o=n.options||[];let i,r;if(i=this.permissionMode===_.AUTO||this.permissionMode!==_.MANUAL&&this.autoApproveTypes.includes(s.type||""),i){let e;for(const t of o){const n=t.optionId||"";if("proceed_once"===n){e=n;break}"proceed_always"===n&&(e=n)}!e&&o.length>0&&(e=o[0].optionId||"proceed_once"),r={outcome:{outcome:"selected",optionId:e}}}else r={outcome:{outcome:"cancelled"}};return void 0!==t&&await this.sendResult(t,r),this.logger.info(`Permission request for tool '${s.title||"unknown"}' - Response: ${r.outcome.outcome}`),{type:"tool_confirmation",params:n,response:r}}async handlePushToolCall(e){const{id:t,params:n}=e,s=`tool_${this.nextRequestId()}`,o={id:s};return void 0!==t&&await this.sendResult(t,o),{type:"tool_call",id:s,params:n}}async handleUpdateToolCall(e){const{id:t,params:n}=e;return void 0!==t&&await this.sendResult(t,null),{type:"tool_update",params:n}}async handleNotifyTaskFinish(e){const{id:t,params:n}=e;return void 0!==t&&await this.sendResult(t,null),{type:"task_finish",params:n}}async handleUnknownMessage(e){const{id:t,method:n,params:s}=e;return this.logger.warn(`Unknown method: ${n}`),void 0!==t&&await this.sendError(t,-32601,"Method not found"),{type:"unknown",method:n,params:s}}}class Y{constructor(e){this.ws=null,this.connected=!1,this.url=e.url,this.logger=e.logger||q,this.timeout=e.timeout||3e5}get isConnected(){return!!this.ws&&this.connected}checkConnected(){if(!this.isConnected)throw new T("Not connected")}async connect(){if(this.connected)this.logger.warn(`Already connected to ${this.url}`);else try{this.logger.info(`Connecting to ${this.url}`),this.ws=await new Promise((e,t)=>{const n=new o(this.url),s=setTimeout(()=>{n.close(),t(new w(`Connected to ${this.url} timeout after ${this.timeout/1e3}s`))},this.timeout);n.on("open",()=>{clearTimeout(s),this.connected=!0,this.logger.info(`Connected to ${this.url} succesfully`),e(n)}),n.on("error",e=>{clearTimeout(s),this.connected=!1,t(e)}),n.on("close",(e,n)=>{clearTimeout(s),this.connected=!1,t(new Error(`${n} (code: ${e})`))})})}catch(e){if(e instanceof w)throw e;throw new T(`Failed to connect to ${this.url}: ${K(e)}`)}}async close(){if(this.ws&&this.connected)try{this.ws.close(),this.logger.info("Connection closed")}catch(e){this.logger.warn(`Error closing connection: ${K(e)}`)}this.ws=null,this.connected=!1}async send(e){this.checkConnected();try{const t="string"==typeof e?e:JSON.stringify(e);await new Promise((e,n)=>{this.ws.send(t,s=>{s?n(s):(this.logger.debug(`Sent message: ${t}`),e())})})}catch(e){throw this.connected=!1,new x(`Failed to send message: ${K(e)}`)}}async*receive(){for(this.checkConnected();this.isConnected;)try{const e=await this.receiveRawData();this.logger.debug(`Received message: ${e}`),yield e}catch(e){if(this.connected=!1,e instanceof T&&e.details.isClosed){this.logger.info("Connection closed");break}throw new x(`Failed to receive message: ${K(e)}`)}}receiveRawData(){return new Promise((e,t)=>{if(!this.isConnected)return void t(new T("Not connected"));const n=()=>{this.ws&&(this.ws.off("close",s),this.ws.off("error",o),this.ws.off("message",i))},s=()=>{n(),this.connected=!1,t(new T("Connection closed",{isClosed:!0}))},o=e=>{n(),this.connected=!1,t(e)},i=t=>{n(),e(t.toString())};this.ws&&(this.ws.on("close",s),this.ws.on("error",o),this.ws.on("message",i))})}}class Z{constructor(e={}){this.cwd=e.cwd||process.cwd(),this.logger=e.logger||q,this.readOnly=e.readOnly||!1,this.maxFileSize=e.maxFileSize||10485760,e.allowedDirs?this.allowedDirs=new Set(e.allowedDirs.map(e=>n.resolve(this.cwd,e))):this.allowedDirs=new Set([this.cwd]),this.logger.info(`File handler initialized with ${this.allowedDirs.size} allowed directories`);for(const e of this.allowedDirs)this.logger.debug(` Allowed: ${e}`)}isPathAllowed(e){try{const t=n.resolve(this.cwd,e);for(const e of this.allowedDirs)if(t.startsWith(e))return!0;return this.logger.warn(`Path not in allowed directories: ${t}`),!1}catch(e){return e instanceof Error&&this.logger.error(`Error checking path: ${e.message}`,e),!1}}async readFile(t,s,o){if(!this.isPathAllowed(t))throw new v(`Access denied: ${t}`);const r=n.resolve(this.cwd,t);try{if(!e.existsSync(r))throw new b(`File not found: ${t}`);try{await i.access(r,e.constants.R_OK)}catch{throw new v(`Permission denied: ${t}`)}const n=await i.stat(r);if(!n.isFile())throw new b(`Not a file: ${t}`);if(n.size>this.maxFileSize)throw new b(`File too large: ${n.size} bytes (max: ${this.maxFileSize})`);const a=await i.readFile(r,"utf-8");if(void 0!==s||void 0!==o){const e=a.split("\n"),n=s?s-1:0,i=o?n+o:e.length,r=Math.max(0,n),c=Math.min(e.length,i);return this.logger.debug(`Read ${c-r} lines from ${t}`),e.slice(r,c).join("\n")}return this.logger.debug(`Read ${a.length} bytes from ${t}`),a}catch(e){if(e instanceof b||e instanceof v)throw e;throw new b(`Failed to read file: ${K(e)}`)}}async writeFile(e,t){if(this.readOnly)throw new v("File system is in read-only mode");if(!this.isPathAllowed(e))throw new v(`Access denied: ${e}`);const s=n.resolve(this.cwd,e);try{await i.mkdir(n.dirname(s),{recursive:!0}),await i.writeFile(s,t,"utf-8"),this.logger.debug(`Wrote ${t.length} bytes to ${e}`)}catch(e){throw new b(`Failed to write file: ${K(e)}`)}}async addAllowedDir(t){const s=n.resolve(this.cwd,t);try{if(!e.existsSync(s))throw new b(`Directory does not exist: ${s}`);if(!(await i.stat(s)).isDirectory())throw new b(`Not a directory: ${s}`);this.allowedDirs.add(s),this.logger.info(`Added allowed directory: ${s}`)}catch(e){if(e instanceof b)throw e;throw new b(`Failed to add ${s} as allowed directory: ${K(e)}`)}}removeAllowedDir(e){const t=n.resolve(this.cwd,e);this.allowedDirs.delete(t),this.logger.info(`Removed allowed directory: ${t}`)}}var ee="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function te(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ne,se,oe,ie,re,ae,ce,le,de={exports:{}},ue={exports:{}};function pe(){if(se)return ne;se=1,ne=s,s.sync=function(t,s){return n(e.statSync(t),t,s)};var e=t;function n(e,t,n){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var n=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!n)return!0;if(-1!==(n=n.split(";")).indexOf(""))return!0;for(var s=0;s<n.length;s++){var o=n[s].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,n)}function s(t,s,o){e.stat(t,function(e,i){o(e,!e&&n(i,t,s))})}return ne}function he(){if(ie)return oe;ie=1,oe=n,n.sync=function(t,n){return s(e.statSync(t),n)};var e=t;function n(t,n,o){e.stat(t,function(e,t){o(e,!e&&s(t,n))})}function s(e,t){return e.isFile()&&function(e,t){var n=e.mode,s=e.uid,o=e.gid,i=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),r=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),d=a|c;return n&l||n&c&&o===r||n&a&&s===i||n&d&&0===i}(e,t)}return oe}function fe(){if(le)return ce;le=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=s,n=e?";":":",o=function(){if(ae)return re;var e;function t(n,s,o){if("function"==typeof s&&(o=s,s={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,o){t(n,s||{},function(t,n){t?o(t):e(n)})})}e(n,s||{},function(e,t){e&&("EACCES"===e.code||s&&s.ignoreErrors)&&(e=null,t=!1),o(e,t)})}return ae=1,e="win32"===process.platform||ee.TESTING_WINDOWS?pe():he(),re=t,t.sync=function(t,n){try{return e.sync(t,n||{})}catch(e){if(n&&n.ignoreErrors||"EACCES"===e.code)return!1;throw e}},re}(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),r=(t,s)=>{const o=s.colon||n,i=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(s.path||process.env.PATH||"").split(o)],r=e?s.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?r.split(o):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:i,pathExt:a,pathExtExe:r}},a=(e,n,s)=>{"function"==typeof n&&(s=n,n={}),n||(n={});const{pathEnv:a,pathExt:c,pathExtExe:l}=r(e,n),d=[],u=s=>new Promise((o,r)=>{if(s===a.length)return n.all&&d.length?o(d):r(i(e));const c=a[s],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=t.join(l,e),h=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;o(p(h,s,0))}),p=(e,t,s)=>new Promise((i,r)=>{if(s===c.length)return i(u(t+1));const a=c[s];o(e+a,{pathExt:l},(o,r)=>{if(!o&&r){if(!n.all)return i(e+a);d.push(e+a)}return i(p(e,t,s+1))})});return s?u(0).then(e=>s(null,e),s):u(0)};return ce=a,a.sync=(e,n)=>{n=n||{};const{pathEnv:s,pathExt:a,pathExtExe:c}=r(e,n),l=[];for(let i=0;i<s.length;i++){const r=s[i],d=/^".*"$/.test(r)?r.slice(1,-1):r,u=t.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(o.sync(t,{pathExt:c})){if(!n.all)return t;l.push(t)}}catch(e){}}}if(n.all&&l.length)return l;if(n.nothrow)return null;throw i(e)},ce}var me,ge,we,ye={exports:{}};function Se(){if(me)return ye.exports;me=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return ye.exports=e,ye.exports.default=e,ye.exports}var Ee,Ie,Te,xe,ve,be,Ae,Oe,Pe,_e,Ce,Re,$e,Ne,Le={};function Fe(){return Te?Ie:(Te=1,Ie=/^#!(.*)/)}function Me(){if(ve)return xe;ve=1;const e=Fe();return xe=(t="")=>{const n=t.match(e);if(!n)return null;const[s,o]=n[0].replace(/#! ?/,"").split(" "),i=s.split("/").pop();return"env"===i?o:o?`${i} ${o}`:i},xe}function ke(){if(Pe)return Oe;Pe=1;const e=s,n=function(){if(we)return ge;we=1;const e=s,t=fe(),n=Se();function o(s,o){const i=s.options.env||process.env,r=process.cwd(),a=null!=s.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(s.options.cwd)}catch(e){}let l;try{l=t.sync(s.command,{path:i[n({env:i})],pathExt:o?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(r)}return l&&(l=e.resolve(a?s.options.cwd:"",l)),l}return ge=function(e){return o(e)||o(e,!0)}}(),o=function(){if(Ee)return Le;Ee=1;const e=/([()\][%!^"`<>&|;, *?])/g;return Le.command=function(t){return t.replace(e,"^$1")},Le.argument=function(t,n){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),n&&(t=t.replace(e,"^$1")),t},Le}(),i=function(){if(Ae)return be;Ae=1;const e=t,n=Me();return be=function(t){const s=Buffer.alloc(150);let o;try{o=e.openSync(t,"r"),e.readSync(o,s,0,150,0),e.closeSync(o)}catch(e){}return n(s.toString())},be}(),r="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(t){if(!r)return t;const s=function(e){e.file=n(e);const t=e.file&&i(e.file);return t?(e.args.unshift(e.file),e.command=t,n(e)):e.file}(t),l=!a.test(s);if(t.options.forceShell||l){const n=c.test(s);t.command=e.normalize(t.command),t.command=o.command(t.command),t.args=t.args.map(e=>o.argument(e,n));const i=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${i}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}return Oe=function(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null);const s={command:e,args:t=t?t.slice(0):[],options:n=Object.assign({},n),file:void 0,original:{command:e,args:t}};return n.shell?s:l(s)},Oe}function Ge(){if(Ce)return _e;Ce=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function n(n,s){return e&&1===n&&!s.file?t(s.original,"spawn"):null}return _e={hookChildProcess:function(t,s){if(!e)return;const o=t.emit;t.emit=function(e,i){if("exit"===e){const e=n(i,s);if(e)return o.call(t,"error",e)}return o.apply(t,arguments)}},verifyENOENT:n,verifyENOENTSync:function(n,s){return e&&1===n&&!s.file?t(s.original,"spawnSync"):null},notFoundError:t},_e}function Ue(){if(Re)return ue.exports;Re=1;const e=d,t=ke(),n=Ge();function s(s,o,i){const r=t(s,o,i),a=e.spawn(r.command,r.args,r.options);return n.hookChildProcess(a,r),a}return ue.exports=s,ue.exports.spawn=s,ue.exports.sync=function(s,o,i){const r=t(s,o,i),a=e.spawnSync(r.command,r.args,r.options);return a.error=a.error||n.verifyENOENTSync(a.status,r),a},ue.exports._parse=t,ue.exports._enoent=n,ue.exports}function De(){return Ne?$e:(Ne=1,$e=e=>{const t="string"==typeof e?"\n":"\n".charCodeAt(),n="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,e.length-1)),e[e.length-1]===n&&(e=e.slice(0,e.length-1)),e})}var je,He={exports:{}};function We(){return je||(je=1,function(e){const t=s,n=Se(),o=e=>{let s;e={cwd:process.cwd(),path:process.env[n()],execPath:process.execPath,...e};let o=t.resolve(e.cwd);const i=[];for(;s!==o;)i.push(t.join(o,"node_modules/.bin")),s=o,o=t.resolve(o,"..");const r=t.resolve(e.cwd,e.execPath,"..");return i.push(r),i.concat(e.path).join(t.delimiter)};e.exports=o,e.exports.default=o,e.exports.env=t=>{const s={...(t={env:process.env,...t}).env},o=n({env:s});return t.path=s[o],s[o]=e.exports(t),s}}(He)),He.exports}var Be,Ke,ze={exports:{}},qe={exports:{}};function Qe(){if(Be)return qe.exports;Be=1;const e=(e,t)=>{for(const n of Reflect.ownKeys(t))Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n));return e};return qe.exports=e,qe.exports.default=e,qe.exports}function Xe(){if(Ke)return ze.exports;Ke=1;const e=Qe(),t=new WeakMap,n=(n,s={})=>{if("function"!=typeof n)throw new TypeError("Expected a function");let o,i=0;const r=n.displayName||n.name||"<anonymous>",a=function(...e){if(t.set(a,++i),1===i)o=n.apply(this,e),n=null;else if(!0===s.throw)throw new Error(`Function \`${r}\` can only be called once`);return o};return e(a,n),t.set(a,i),a};return ze.exports=n,ze.exports.default=n,ze.exports.callCount=e=>{if(!t.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return t.get(e)},ze.exports}var Ve,Je={},Ye={},Ze={};var et,tt,nt,st,ot,it={};function rt(){if(et)return it;et=1,Object.defineProperty(it,"__esModule",{value:!0}),it.SIGRTMAX=it.getRealtimeSignals=void 0;it.getRealtimeSignals=function(){const s=n-t+1;return Array.from({length:s},e)};const e=function(e,n){return{name:`SIGRT${n+1}`,number:t+n,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},t=34,n=64;return it.SIGRTMAX=n,it}function at(){if(tt)return Ye;tt=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.getSignals=void 0;var e=a,t=(Ve||(Ve=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.SIGNALS=void 0,Ze.SIGNALS=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}]),Ze),n=rt();Ye.getSignals=function(){const e=(0,n.getRealtimeSignals)();return[...t.SIGNALS,...e].map(s)};const s=function({name:t,number:n,description:s,action:o,forced:i=!1,standard:r}){const{signals:{[t]:a}}=e.constants,c=void 0!==a;return{name:t,number:c?a:n,description:s,supported:c,action:o,forced:i,standard:r}};return Ye}function ct(){if(ot)return st;ot=1;const{signalsByName:e}=function(){if(nt)return Je;nt=1,Object.defineProperty(Je,"__esModule",{value:!0}),Je.signalsByNumber=Je.signalsByName=void 0;var e=a,t=at(),n=rt();const s=function(e,{name:t,number:n,description:s,supported:o,action:i,forced:r,standard:a}){return{...e,[t]:{name:t,number:n,description:s,supported:o,action:i,forced:r,standard:a}}},o=(0,t.getSignals)().reduce(s,{});Je.signalsByName=o;const i=function(e,t){const n=r(e,t);if(void 0===n)return{};const{name:s,description:o,supported:i,action:a,forced:c,standard:l}=n;return{[e]:{name:s,number:e,description:o,supported:i,action:a,forced:c,standard:l}}},r=function(t,n){const s=n.find(({name:n})=>e.constants.signals[n]===t);return void 0!==s?s:n.find(e=>e.number===t)},c=function(){const e=(0,t.getSignals)(),s=n.SIGRTMAX+1,o=Array.from({length:s},(t,n)=>i(n,e));return Object.assign({},...o)}();return Je.signalsByNumber=c,Je}();return st=({stdout:t,stderr:n,all:s,error:o,signal:i,exitCode:r,command:a,escapedCommand:c,timedOut:l,isCanceled:d,killed:u,parsed:{options:{timeout:p}}})=>{r=null===r?void 0:r;const h=void 0===(i=null===i?void 0:i)?void 0:e[i].description,f=(({timedOut:e,timeout:t,errorCode:n,signal:s,signalDescription:o,exitCode:i,isCanceled:r})=>e?`timed out after ${t} milliseconds`:r?"was canceled":void 0!==n?`failed with ${n}`:void 0!==s?`was killed with ${s} (${o})`:void 0!==i?`failed with exit code ${i}`:"failed")({timedOut:l,timeout:p,errorCode:o&&o.code,signal:i,signalDescription:h,exitCode:r,isCanceled:d}),m=`Command ${f}: ${a}`,g="[object Error]"===Object.prototype.toString.call(o),w=g?`${m}\n${o.message}`:m,y=[w,n,t].filter(Boolean).join("\n");return g?(o.originalMessage=o.message,o.message=y):o=new Error(y),o.shortMessage=w,o.command=a,o.escapedCommand=c,o.exitCode=r,o.signal=i,o.signalDescription=h,o.stdout=t,o.stderr=n,void 0!==s&&(o.all=s),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=Boolean(l),o.isCanceled=d,o.killed=u&&!l,o},st}var lt,dt={exports:{}};function ut(){if(lt)return dt.exports;lt=1;const e=["stdin","stdout","stderr"],t=t=>{if(!t)return;const{stdio:n}=t;if(void 0===n)return e.map(e=>t[e]);if((t=>e.some(e=>void 0!==t[e]))(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${e.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof n)return n;if(!Array.isArray(n))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof n}\``);const s=Math.max(n.length,e.length);return Array.from({length:s},(e,t)=>n[t])};return dt.exports=t,dt.exports.node=e=>{const n=t(e);return"ipc"===n?"ipc":void 0===n||"string"==typeof n?[n,n,n,"ipc"]:n.includes("ipc")?n:[...n,"ipc"]},dt.exports}var pt,ht,ft,mt,gt,wt,yt={exports:{}},St={exports:{}};function Et(){return pt||(pt=1,(e=St).exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],"win32"!==process.platform&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")),St.exports;var e}function It(){if(mt)return ft;mt=1;const e=a,t=function(){if(ht)return yt.exports;ht=1;var e=ee.process;const t=function(e){return e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on};if(t(e)){var n,s=u,o=Et(),i=/^win/i.test(e.platform),r=p;"function"!=typeof r&&(r=r.EventEmitter),e.__signal_exit_emitter__?n=e.__signal_exit_emitter__:((n=e.__signal_exit_emitter__=new r).count=0,n.emitted={}),n.infinite||(n.setMaxListeners(1/0),n.infinite=!0),yt.exports=function(e,o){if(!t(ee.process))return function(){};s.equal(typeof e,"function","a callback must be provided for exit handler"),!1===d&&h();var i="exit";return o&&o.alwaysLast&&(i="afterexit"),n.on(i,e),function(){n.removeListener(i,e),0===n.listeners("exit").length&&0===n.listeners("afterexit").length&&a()}};var a=function(){d&&t(ee.process)&&(d=!1,o.forEach(function(t){try{e.removeListener(t,l[t])}catch(e){}}),e.emit=g,e.reallyExit=f,n.count-=1)};yt.exports.unload=a;var c=function(e,t,s){n.emitted[e]||(n.emitted[e]=!0,n.emit(e,t,s))},l={};o.forEach(function(s){l[s]=function(){t(ee.process)&&e.listeners(s).length===n.count&&(a(),c("exit",null,s),c("afterexit",null,s),i&&"SIGHUP"===s&&(s="SIGINT"),e.kill(e.pid,s))}}),yt.exports.signals=function(){return o};var d=!1,h=function(){!d&&t(ee.process)&&(d=!0,n.count+=1,o=o.filter(function(t){try{return e.on(t,l[t]),!0}catch(e){return!1}}),e.emit=w,e.reallyExit=m)};yt.exports.load=h;var f=e.reallyExit,m=function(n){t(ee.process)&&(e.exitCode=n||0,c("exit",e.exitCode,null),c("afterexit",e.exitCode,null),f.call(e,e.exitCode))},g=e.emit,w=function(n,s){if("exit"===n&&t(ee.process)){void 0!==s&&(e.exitCode=s);var o=g.apply(this,arguments);return c("exit",e.exitCode,null),c("afterexit",e.exitCode,null),o}return g.apply(this,arguments)}}else yt.exports=function(){return function(){}};return yt.exports}(),n=(e,t,n,o)=>{if(!s(t,n,o))return;const r=i(n),a=setTimeout(()=>{e("SIGKILL")},r);a.unref&&a.unref()},s=(e,{forceKillAfterTimeout:t},n)=>o(e)&&!1!==t&&n,o=t=>t===e.constants.signals.SIGTERM||"string"==typeof t&&"SIGTERM"===t.toUpperCase(),i=({forceKillAfterTimeout:e=!0})=>{if(!0===e)return 5e3;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e};return ft={spawnedKill:(e,t="SIGTERM",s={})=>{const o=e(t);return n(e,t,s,o),o},spawnedCancel:(e,t)=>{e.kill()&&(t.isCanceled=!0)},setupTimeout:(e,{timeout:t,killSignal:n="SIGTERM"},s)=>{if(0===t||void 0===t)return s;let o;const i=new Promise((s,i)=>{o=setTimeout(()=>{((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))})(e,n,i)},t)}),r=s.finally(()=>{clearTimeout(o)});return Promise.race([i,r])},validateTimeout:({timeout:e})=>{if(void 0!==e&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},setExitHandler:async(e,{cleanup:n,detached:s},o)=>{if(!n||s)return o;const i=t(()=>{e.kill()});return o.finally(()=>{i()})}}}var Tt,xt,vt,bt,At,Ot,Pt,_t,Ct,Rt,$t,Nt,Lt={exports:{}};function Ft(){if(xt)return Tt;xt=1;const{PassThrough:e}=f;return Tt=t=>{t={...t};const{array:n}=t;let{encoding:s}=t;const o="buffer"===s;let i=!1;n?i=!(s||o):s=s||"utf8",o&&(s=null);const r=new e({objectMode:i});s&&r.setEncoding(s);let a=0;const c=[];return r.on("data",e=>{c.push(e),i?a=c.length:a+=e.length}),r.getBufferedValue=()=>n?c:o?Buffer.concat(c,a):c.join(""),r.getBufferedLength=()=>a,r},Tt}function Mt(){if(vt)return Lt.exports;vt=1;const{constants:e}=h,t=f,{promisify:n}=m,s=Ft(),o=n(t.pipeline);class i extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function r(t,n){if(!t)throw new Error("Expected a stream");n={maxBuffer:1/0,...n};const{maxBuffer:r}=n,a=s(n);return await new Promise((n,s)=>{const c=t=>{t&&a.getBufferedLength()<=e.MAX_LENGTH&&(t.bufferedData=a.getBufferedValue()),s(t)};(async()=>{try{await o(t,a),n()}catch(e){c(e)}})(),a.on("data",()=>{a.getBufferedLength()>r&&c(new i)})}),a.getBufferedValue()}return Lt.exports=r,Lt.exports.buffer=(e,t)=>r(e,{...t,encoding:"buffer"}),Lt.exports.array=(e,t)=>r(e,{...t,array:!0}),Lt.exports.MaxBufferError=i,Lt.exports}function kt(){if(At)return bt;At=1;const{PassThrough:e}=f;return bt=function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=s,n.isEmpty=function(){return 0==t.length},n.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(s),n;function s(e){return Array.isArray(e)?(e.forEach(s),this):(t.push(e),e.once("end",o.bind(null,e)),e.once("error",n.emit.bind(n,"error")),e.pipe(n,{end:!1}),this)}function o(e){!(t=t.filter(function(t){return t!==e})).length&&n.readable&&n.end()}},bt}function Gt(){if(Pt)return Ot;Pt=1;const e=function(){if(wt)return gt;wt=1;const e=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;return e.writable=t=>e(t)&&!1!==t.writable&&"function"==typeof t._write&&"object"==typeof t._writableState,e.readable=t=>e(t)&&!1!==t.readable&&"function"==typeof t._read&&"object"==typeof t._readableState,e.duplex=t=>e.writable(t)&&e.readable(t),e.transform=t=>e.duplex(t)&&"function"==typeof t._transform,gt=e}(),t=Mt(),n=kt(),s=async(e,t)=>{if(e){e.destroy();try{return await t}catch(e){return e.bufferedData}}},o=(e,{encoding:n,buffer:s,maxBuffer:o})=>{if(e&&s)return n?t(e,{encoding:n,maxBuffer:o}):t.buffer(e,{maxBuffer:o})};return Ot={handleInput:(t,n)=>{void 0!==n&&void 0!==t.stdin&&(e(n)?n.pipe(t.stdin):t.stdin.end(n))},makeAllStream:(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const s=n();return e.stdout&&s.add(e.stdout),e.stderr&&s.add(e.stderr),s},getSpawnedResult:async({stdout:e,stderr:t,all:n},{encoding:i,buffer:r,maxBuffer:a},c)=>{const l=o(e,{encoding:i,buffer:r,maxBuffer:a}),d=o(t,{encoding:i,buffer:r,maxBuffer:a}),u=o(n,{encoding:i,buffer:r,maxBuffer:2*a});try{return await Promise.all([c,l,d,u])}catch(o){return Promise.all([{error:o,signal:o.signal,timedOut:o.timedOut},s(e,l),s(t,d),s(n,u)])}},validateInputSync:({input:t})=>{if(e(t))throw new TypeError("The `input` option cannot be a stream in sync mode")}},Ot}function Ut(){if($t)return Rt;$t=1;const e=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],t=/^[\w.-]+$/,n=/"/g,s=/ +/g;return Rt={joinCommand:(t,n)=>e(t,n).join(" "),getEscapedCommand:(s,o)=>e(s,o).map(e=>(e=>"string"!=typeof e||t.test(e)?e:`"${e.replace(n,'\\"')}"`)(e)).join(" "),parseCommand:e=>{const t=[];for(const n of e.trim().split(s)){const e=t[t.length-1];e&&e.endsWith("\\")?t[t.length-1]=`${e.slice(0,-1)} ${n}`:t.push(n)}return t}}}var Dt,jt=function(){if(Nt)return de.exports;Nt=1;const e=s,t=d,n=Ue(),o=De(),i=We(),r=Xe(),a=ct(),c=ut(),{spawnedKill:l,spawnedCancel:u,setupTimeout:p,validateTimeout:h,setExitHandler:f}=It(),{handleInput:m,getSpawnedResult:g,makeAllStream:w,validateInputSync:y}=Gt(),{mergePromise:S,getSpawnedPromise:E}=function(){if(Ct)return _t;Ct=1;const e=(async()=>{})().constructor.prototype,t=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(e,t)]);return _t={mergePromise:(e,n)=>{for(const[s,o]of t){const t="function"==typeof n?(...e)=>Reflect.apply(o.value,n(),e):o.value.bind(n);Reflect.defineProperty(e,s,{...o,value:t})}return e},getSpawnedPromise:e=>new Promise((t,n)=>{e.on("exit",(e,n)=>{t({exitCode:e,signal:n})}),e.on("error",e=>{n(e)}),e.stdin&&e.stdin.on("error",e=>{n(e)})})},_t}(),{joinCommand:I,parseCommand:T,getEscapedCommand:x}=Ut(),v=(t,s,o={})=>{const r=n._parse(t,s,o);return t=r.command,s=r.args,(o={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(o=r.options).cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...o}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:s,execPath:o})=>{const r=t?{...process.env,...e}:e;return n?i.env({env:r,cwd:s,execPath:o}):r})(o),o.stdio=c(o),"win32"===process.platform&&"cmd"===e.basename(t,".exe")&&s.unshift("/q"),{file:t,args:s,options:o,parsed:r}},b=(e,t,n)=>"string"==typeof t||Buffer.isBuffer(t)?e.stripFinalNewline?o(t):t:void 0===n?void 0:"",A=(e,n,s)=>{const o=v(e,n,s),i=I(e,n),c=x(e,n);let d;h(o.options);try{d=t.spawn(o.file,o.args,o.options)}catch(e){const n=new t.ChildProcess,s=Promise.reject(a({error:e,stdout:"",stderr:"",all:"",command:i,escapedCommand:c,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return S(n,s)}const y=E(d),T=p(d,o.options,y),A=f(d,o.options,T),O={isCanceled:!1};d.kill=l.bind(null,d.kill.bind(d)),d.cancel=u.bind(null,d,O);const P=r(async()=>{const[{error:e,exitCode:t,signal:n,timedOut:s},r,l,u]=await g(d,o.options,A),p=b(o.options,r),h=b(o.options,l),f=b(o.options,u);if(e||0!==t||null!==n){const r=a({error:e,exitCode:t,signal:n,stdout:p,stderr:h,all:f,command:i,escapedCommand:c,parsed:o,timedOut:s,isCanceled:O.isCanceled,killed:d.killed});if(!o.options.reject)return r;throw r}return{command:i,escapedCommand:c,exitCode:0,stdout:p,stderr:h,all:f,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return m(d,o.options.input),d.all=w(d,o.options),S(d,P)};return de.exports=A,de.exports.sync=(e,n,s)=>{const o=v(e,n,s),i=I(e,n),r=x(e,n);let c;y(o.options);try{c=t.spawnSync(o.file,o.args,o.options)}catch(e){throw a({error:e,stdout:"",stderr:"",all:"",command:i,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const l=b(o.options,c.stdout,c.error),d=b(o.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=a({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:i,escapedCommand:r,parsed:o,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!o.options.reject)return e;throw e}return{command:i,escapedCommand:r,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},de.exports.command=(e,t)=>{const[n,...s]=T(e);return A(n,s,t)},de.exports.commandSync=(e,t)=>{const[n,...s]=T(e);return A.sync(n,s,t)},de.exports.node=(e,t,n={})=>{t&&!Array.isArray(t)&&"object"==typeof t&&(n=t,t=[]);const s=c.node(n),o=process.execArgv.filter(e=>!e.startsWith("--inspect")),{nodePath:i=process.execPath,nodeOptions:r=o}=n;return A(i,[...r,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:s,shell:!1})},de.exports}(),Ht=te(jt);class Wt{constructor(e={}){this.port=null,this.process=null,this.iflowPath=null,this.exitHandler=null,this.isCleaningUp=!1,this.logger=e.logger||q,this.startPort=e.startPort||8090}get url(){if(!this.port)throw new E("iFlow process not started");return`ws://localhost:${this.port}/acp`}isRunning(){return!!this.process&&!this.process.killed&&null===this.process.exitCode}isWindows(){return"win32"===r.platform()}which(e){try{const t=this.isWindows()?"where":"which",n=l.execSync(`${t} ${e}`,{encoding:"utf-8",windowsHide:!0});return n.trim().split("\n")[0].trim()||null}catch{return null}}fileExists(t){try{return e.existsSync(t)&&e.statSync(t).isFile()}catch{return!1}}getFallbackLocations(){const e=r.homedir(),t=r.platform();if(this.isWindows())return[n.join(e,"AppData","Roaming","npm","iflow.cmd"),n.join(e,"AppData","Local","npm","iflow.cmd"),n.join(e,"AppData","Roaming","npm","iflow.exe"),n.join("C:","Program Files","nodejs","iflow.cmd"),n.join("C:","Program Files (x86)","nodejs","iflow.cmd"),n.join(e,".npm-global","iflow.cmd"),n.join(e,"node_modules",".bin","iflow.cmd")];{const s=["/usr/local/bin/iflow",n.join(e,".npm-global","bin","iflow"),n.join(e,".local","bin","iflow"),n.join(e,"node_modules",".bin","iflow"),n.join(e,".yarn","bin","iflow"),n.join(e,".config","yarn","global","node_modules",".bin","iflow"),n.join(e,".local","share","pnpm","iflow"),"/usr/bin/iflow"];return"darwin"===t&&"arm64"===r.arch()&&s.unshift("/opt/homebrew/bin/iflow"),s}}findIflowPath(){let e=this.which("iflow");if(e){if(this.isWindows()&&!e.endsWith(".cmd")&&!e.endsWith(".exe")){const t=e+".cmd";this.fileExists(t)&&(e=t)}return this.logger.debug(`Found iflow at: ${e}`),e}const t=this.getFallbackLocations();for(const e of t)if(this.fileExists(e))return this.logger.debug(`Found iflow at: ${e}`),e;const n=null!==this.which("npm"),s=null!==this.which("node");let o;throw o=this.isWindows()?n||s?"iFlow CLI not found. Please install it using one of the following commands:\n\nUsing npm (recommended):\n npm install -g @iflow-ai/iflow-cli@latest\n\nUsing Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\nUsing pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\nAfter installation, please restart your terminal or command prompt.":"iFlow requires Node.js, but it is not installed on your system.\n\nPlease install Node.js first: https://nodejs.org/\n\nAfter installing Node.js, install iFlow with:\n npm install -g @iflow-ai/iflow-cli@latest":'iFlow CLI not found. Please install it using one of the following methods:\n\nš Mac/Linux users (recommended installation script):\n bash -c "$(curl -fsSL https://cloud.iflow.cn/iflow-cli/install.sh)"\n\nOr using npm:\n npm install -g @iflow-ai/iflow-cli@latest\n\nOr using Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\nOr using pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\nš§ Ubuntu/Debian users may need:\n sudo npm install -g @iflow-ai/iflow-cli@latest',new S(o)}isPortAvailable(e,t=1e3){return new Promise(n=>{const s=c.createServer(),o=setTimeout(()=>{s.close(),n(!1)},t);s.listen(e,"localhost",()=>{clearTimeout(o),s.once("close",()=>{n(!0)}),s.close()}),s.once("error",()=>{clearTimeout(o),n(!1)})})}async findAvailablePort(){for(let e=0;e<10;e++){const t=this.startPort+e;if(await this.isPortAvailable(t))return this.logger.debug(`Found available port: ${t}`),t}throw new I(`No available port found in range ${this.startPort}-${this.startPort+10-1}. Please specify a different port range or free up some ports.`)}async start(){if(this.isRunning())return this.url;this.iflowPath=this.findIflowPath(),this.port=await this.findAvailablePort();const e=[this.iflowPath,"--experimental-acp","--port",this.port.toString()];this.logger.info(`Starting iFlow process: ${e.join(" ")}`);try{if(this.process=Ht(e[0],e.slice(1),{stdio:["ignore","pipe","pipe"],detached:!1,cleanup:!0,windowsHide:!0,reject:!1}),await this.onSpawn(),!this.isRunning()){let e="iFlow process exited immediately";throw this.process.stderr&&(e+=`: ${this.process.stderr}`),new Error(e)}return this.registerExitHandler(),this.logger.info(`iFlow process started on port ${this.port} (PID: ${this.process.pid})`),this.url}catch(e){throw this.port=null,this.process=null,new E(`Failed to start iFlow process: ${K(e)}`)}}registerExitHandler(){this.exitHandler||(this.exitHandler=()=>{if(!this.isCleaningUp&&this.process&&this.isRunning()){this.isCleaningUp=!0,this.logger.debug("Parent process exiting, cleaning up child process");try{if(this.isWindows())try{l.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:Wt.TASKKILL_TIMEOUT_EXIT_HANDLER,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill failed: ${K(e)}`)}else this.process.kill("SIGKILL")}catch(e){this.logger.debug(`Error during process cleanup: ${K(e)}`)}finally{this.isCleaningUp=!1}}},process.on("exit",this.exitHandler),process.on("SIGINT",this.exitHandler),process.on("SIGTERM",this.exitHandler),this.isWindows()&&process.on("SIGBREAK",this.exitHandler))}unregisterExitHandler(){this.exitHandler&&(process.off("exit",this.exitHandler),process.off("SIGINT",this.exitHandler),process.off("SIGTERM",this.exitHandler),this.isWindows()&&process.off("SIGBREAK",this.exitHandler),this.exitHandler=null)}async stop(){if(this.process){if(this.unregisterExitHandler(),!this.isRunning())return this.port=null,void(this.process=null);this.logger.info(`Stopping iFlow process (PID: ${this.process.pid})`);try{if(this.isWindows())try{l.execSync(`taskkill /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:3e3,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill (graceful shutdown) failed: ${K(e)}`)}else this.process.kill("SIGTERM");if(await Promise.race([this.process.then(()=>{},()=>{}),new Promise(e=>setTimeout(()=>e(),5e3))]),this.isRunning()){if(this.logger.warn("iFlow process did not terminate gracefully, forcing kill"),this.isWindows())try{l.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:Wt.TASKKILL_TIMEOUT_STOP,stdio:"ignore"})}catch(e){this.logger.warn(`taskkill /F /T failed, process may have already exited or is inaccessible: ${K(e)}`)}else this.process.kill("SIGKILL");await this.process.then(()=>{},()=>{})}else this.logger.info("iFlow process terminated gracefully")}catch(e){this.logger.error(`Error stopping iFlow process: ${K(e)}`)}finally{this.port=null,this.process=null}}}async onSpawn(e=5e3){return new Promise((t,n)=>{if(!this.process)return void n(new Error("Process not initialized"));const s=setTimeout(()=>{n(new Error(`Process spawn timeout after ${e}ms`))},e);this.process.once("spawn",()=>{clearTimeout(s),setTimeout(t,2e3)})})}}Wt.TASKKILL_TIMEOUT_EXIT_HANDLER=3e3,Wt.TASKKILL_TIMEOUT_STOP=5e3,function(e){e.ERROR="error",e.RESPONSE="response",e.FILE_READ="file_read",e.FILE_WRITE="file_write",e.SESSION_UPDATE="session_update",e.TOOL_CALL="tool_call",e.TOOL_UPDATE="tool_update",e.TOOL_CONFIRMATION="tool_confirmation",e.TASK_FINISH="task_finish",e.UNKNOWN="unknown"}(Dt||(Dt={}));class Bt{constructor(e={}){this.protocol=null,this.transport=null,this.connected=!1,this.authenticated=!1,this.messageTask=null,this.messageQueue=[],this.pendingToolCalls=new Map,this.url=null,this.sessionId=null,this.processManager=null,this.processStarted=!1,this.options={url:"ws://localhost:8090/acp",cwd:process.cwd(),timeout:3e4,logLevel:"INFO",fileMaxSize:10485760,permissionMode:_.AUTO,autoApproveTypes:["read","fetch","list"],authMethodId:"iflow",autoStartProcess:!0,processStartPort:8090,...e},this.logger=new z({level:this.options.logLevel})}async connect(){if(this.connected)this.logger.warn("Already connected");else try{if(this.options.autoStartProcess&&(this.options.url?.startsWith("ws://localhost:")||this.options.url?.startsWith("ws://127.0.0.1:"))){const e=new Y({url:this.options.url,logger:this.logger,timeout:2e3});try{await e.connect(),await e.close(),this.url=this.options.url,this.logger.info(`iFlow already running at ${this.options.url}`)}catch{this.logger.info("iFlow not running, starting process..."),this.processManager=new Wt({logger:this.logger,startPort:this.options.processStartPort});try{const e=await this.processManager.start();this.url=e,this.processStarted=!0,this.logger.info(`Started iFlow process at ${e}`),await new Promise(e=>setTimeout(e,1e3))}catch(e){throw e instanceof S?(this.logger.error("iFlow not installed"),S):(this.logger.error(`Failed to start iFlow process: ${K(e)}`),new T(`Failed to start iFlow process: ${K(e)}`))}}}let e=null;this.options.fileAccess&&(e=new Z({cwd:this.options.cwd,logger:this.logger,readOnly:this.options.fileReadOnly,maxFileSize:this.options.fileMaxSize,allowedDirs:this.options.fileAllowedDirs}),this.logger.info(`File system access enabled with ${this.options.fileReadOnly?"read-only":"read-write"} mode`)),this.transport=new Y({url:this.options.url,logger:this.logger,timeout:this.options.timeout}),this.protocol=new J({logger:this.logger,transport:this.transport,fileHandler:e,permissionMode:this.options.permissionMode,autoApproveTypes:this.options.autoApproveTypes}),await this.transport.connect();const t=await this.protocol.initialize({mcpServers:this.options.mcpServers,hooks:this.options.hooks,commands:this.options.commands,agents:this.options.agents});this.authenticated=t.isAuthenticated||!1,this.authenticated||(await this.protocol.authenticate({methodId:this.options.authMethodId,methodInfo:this.options.authMethodInfo}),this.authenticated=!0),this.sessionId=await this.protocol.createSession({cwd:this.options.cwd||process.cwd(),mcpServers:this.options.mcpServers,hooks:this.options.hooks,commands:this.options.commands,agents:this.options.agents,settings:this.options.sessionSettings}),this.connected=!0,this.messageTask=this.handleMessages(),this.logger.info("Connected to iFlow")}catch(e){throw await this.disconnect(),new T(`Failed to connect: ${K(e)}`)}}async loadSession(e){if(!this.connected||!this.protocol)throw new T("Not connected. Call connect() first.");await this.protocol.loadSession({sessionId:e,cwd:this.options.cwd||process.cwd(),mcpServers:this.options.mcpServers}),this.sessionId=e,this.logger.info(`Loaded session: ${e}`)}async disconnect(){this.connected=!1,this.transport&&await this.transport.close(),this.processManager&&this.processStarted&&await this.processManager.stop(),this.url=null,this.protocol=null,this.transport=null,this.messageTask=null,this.authenticated=!1,this.processManager=null,this.processStarted=!1,this.logger.info("Disconnected from iFlow")}async sendMessage(t,s){if(!this.connected||!this.protocol||!this.sessionId)throw new T("Not connected. Call connect() first.");const o=[{type:"text",text:t}];if(s?.length)for(const t of s){const s=n.resolve(this.options.cwd||process.cwd(),t),i=n.parse(t);if(!e.existsSync(s)){this.logger.warn(`File not found, skipping: ${s}`);continue}const r=i.ext.toLowerCase();if([".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg"].includes(r))try{const t=e.readFileSync(s).toString("base64"),n={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".bmp":"image/bmp",".webp":"image/webp",".svg":"image/svg+xml"};o.push({type:"image",data:t,mimeType:n[r]||"image/unknown"}),this.logger.debug(`Added image file: ${i.base}`)}catch(e){this.logger.error(`Failed to read image file ${s}: ${K(e)}`);continue}else if([".mp3",".wav",".m4a",".ogg",".flac"].includes(r))try{const t=e.readFileSync(s).toString("base64"),n={".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".flac":"audio/flac"};o.push({type:"audio",data:t,mimeType:n[r]||"audio/unknown"}),this.logger.debug(`Added audio file: ${i.base}`)}catch(e){this.logger.error(`Failed to read audio file ${s}: ${K(e)}`);continue}else{const t=e.statSync(s);o.push({type:"resource_link",uri:`file://${s}`,name:i.base,title:i.name,size:t.size}),this.logger.debug(`Added resource link: ${i.base}`)}}await this.protocol.sendPrompt({sessionId:this.sessionId,prompt:o})}async interrupt(){if(!this.connected||!this.protocol||!this.sessionId)throw new T("Not connected");await this.protocol.cancelSession({sessionId:this.sessionId}),this.logger.info("Sent interrupt signal")}async*receiveMessages(){if(!this.connected)throw new T("Not connected");for(;this.connected;)try{this.messageQueue.length>0?yield this.messageQueue.shift():await new Promise(e=>setTimeout(e,100))}catch{continue}}async approveToolCall(e,t=G.ALLOW){if(!this.pendingToolCalls.has(e))throw new Error(`Unknown tool call: ${e}`);this.logger.info(`Approved tool call ${e} with outcome ${t}`),this.pendingToolCalls.delete(e)}async rejectToolCall(e){if(!this.pendingToolCalls.has(e))throw new Error(`Unknown tool call: ${e}`);this.logger.info(`Rejected tool call ${e}`),this.pendingToolCalls.delete(e)}async handleMessages(){if(this.protocol)try{for await(const e of this.protocol.handleMessages()){const t=this.processProtocolMessage(e);t&&this.messageQueue.push(t)}}catch(e){this.logger.error(`Error in message handler: ${K(e)}`);const t={type:D.ERROR,code:-1,message:String(K(e))};this.messageQueue.push(t)}}processProtocolMessage(e){switch(e.type){case Dt.SESSION_UPDATE:{const{updateData:t}=e;let n,s;switch("agentId"in t&&t.agentId&&(n=t.agentId,s=function(e){const t=e.split("-");return"subagent"!==t[0]||t.length<4?{agentId:e}:4===t.length?{agentId:e,taskId:["null","undefined"].includes(t[1])?void 0:t[1],agentIndex:parseInt(t[2])||void 0,timestamp:parseInt(t[3])||void 0}:{agentId:e,taskId:t.slice(1,-2).join("-"),agentIndex:parseInt(t[t.length-2])||void 0,timestamp:parseInt(t[t.length-1])||void 0}}(n)),t.sessionUpdate){case B.PLAN:{const e=t.entries?.map(e=>({content:e.content||"",status:e.status||N.PENDING,priority:e.priority||$.MEDIUM}));return e&&e?.length>0?{type:D.PLAN,entries:e}:null}case B.TOOL_CALL:{const e={type:D.TOOL_CALL,id:t.toolCallId||"",label:t.title||"Tool",icon:{type:U.EMOJI,value:"š§"},status:t.status||F.IN_PROGRESS,toolName:t.toolName,args:t.args};return n&&(e.agentId=n,e.agentInfo=s),this.pendingToolCalls.set(e.id,e),{...e}}case B.TOOL_CALL_UPDATE:{const e=t.toolCallId;let o;if(this.pendingToolCalls.has(e)?(o=this.pendingToolCalls.get(e),o.status=t.status||F.COMPLETED,t.toolName&&(o.toolName=t.toolName),!o.agentId&&n&&(o.agentId=n),!o.agentInfo&&s&&(o.agentInfo=s)):(o={type:D.TOOL_CALL,id:e,label:t.title||"Tool",icon:{type:U.EMOJI,value:"š§"},status:t.status||F.COMPLETED,toolName:t.toolName},n&&(o.agentId=n,o.agentInfo=s),this.pendingToolCalls.set(e,o)),t.content&&t.content?.length>0){let e;const n=[];for(const s of t.content)"args"in s&&(e=s.args),"content"===s.type&&"text"===s.content?.type&&n.push(s.content.text||"");void 0!==e&&(o.args=e),n.length>0&&(o.output=n.join("\n"))}return{...o}}case B.USER_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t)return{type:D.USER,chunks:[{text:t}]}}return null}case B.AGENT_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:D.ASSISTANT,chunk:{text:t}};return n&&(e.agentId=n,e.agentInfo=s),e}}return null}case B.AGENT_THOUGHT_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:D.ASSISTANT,chunk:{thought:t}};return n&&(e.agentId=n,e.agentInfo=s),e}}}default:return null}}case Dt.RESPONSE:return"stopReason"in(e.result||{})?{type:D.TASK_FINISH,stopReason:e.result.stopReason}:null;case Dt.ERROR:return{type:D.ERROR,code:e.code||-1,message:e.error||"Unknown error"};default:return null}}}function Kt(e){let t,n=!1,s="text";if(e.startsWith("//"))n=!0,s="control";else try{t=JSON.parse(e),t&&"method"in t?s=`method:${t.method}`:t&&("result"in t||"error"in t)?s="response":t&&"type"in t&&(s=t.type)}catch{}return{isControl:n,messageType:s,rawData:e,jsonData:t,timestamp:Date.now()}}class zt extends Bt{constructor(e,t=!0){super(e),this.rawQueue=[],this.rawHistory=[],this.rawQueueResolvers=[],this.messageQueueResolvers=[],this.captureRaw=t}async handleMessages(){if(this.protocol)try{if(this.captureRaw&&this.transport){const e=this.captureRawStream(),t=this.handleParsedStream();await Promise.all([e,t])}else await super.handleMessages()}catch(e){this.logger.error(`Error in message handler: ${K(e)}`)}}async captureRawStream(){if(this.transport)try{for await(const e of this.transport.receive()){const t=Kt("string"==typeof e?e:JSON.stringify(e));this.rawQueue.push(t),this.rawHistory.push(t);const n=this.rawQueueResolvers.shift();n&&n(t)}}catch(e){this.logger.error(`Error capturing raw stream: ${K(e)}`)}}async handleParsedStream(){if(this.protocol)for await(const e of this.protocol.handleMessages()){const t=this.processProtocolMessage(e);if(t){const e=this.messageQueueResolvers.shift();e&&e(t)}}}async*receiveRawMessages(){for(;this.connected||this.rawQueue.length>0;)try{if(this.rawQueue.length>0)yield this.rawQueue.shift();else{const e=await Promise.race([new Promise(e=>{this.rawQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),100)})]);yield e}}catch(e){if(e instanceof Error&&"Timeout"===e.message)continue;throw e}}async*receiveDualStream(){const e=[],t=[];for(;this.connected||this.rawQueue.length>0||e.length>0||t.length>0;)try{let e,t;e=this.rawQueue.length>0?this.rawQueue.shift():await Promise.race([new Promise(e=>{this.rawQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),10)})]);try{t=await Promise.race([new Promise(e=>{this.messageQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),10)})])}catch{}e.parsedMessage=t,yield[e,t]}catch(e){if(!(e instanceof Error&&"Timeout"===e.message))throw e;try{const e=await Promise.race([new Promise(e=>{this.messageQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),10)})]),t=Kt("<no-raw-data>");t.messageType="parsed_only",yield[t,e]}catch(e){if(e instanceof Error&&"Timeout"===e.message)continue;throw e}}}getRawHistory(){return[...this.rawHistory]}getProtocolStats(){const e={totalMessages:this.rawHistory.length,messageTypes:{},controlMessages:0,jsonMessages:0,textMessages:0,errors:0};for(const t of this.rawHistory)t.messageType&&(e.messageTypes[t.messageType]=(e.messageTypes[t.messageType]||0)+1),t.isControl?e.controlMessages++:t.jsonData?e.jsonMessages++:e.textMessages++,t.jsonData&&"error"in t.jsonData&&e.errors++;return e}async sendRaw(e){if(!this.transport)throw new Error("Not connected");await this.transport.send(e);const t="string"==typeof e?e:JSON.stringify(e).substring(0,100);this.logger.info(`Sent raw data: ${t}`)}}async function qt(e,t,n){const s=[],o=new Bt(n);await o.connect();try{await o.sendMessage(e,t);for await(const e of o.receiveMessages())if(e.type===D.ASSISTANT&&e.chunk.text)s.push(e.chunk.text);else if(e.type===D.TASK_FINISH)break}finally{await o.disconnect()}return s.join("")}async function*Qt(e,t,n){const s=new Bt(n);await s.connect();try{await s.sendMessage(e,t);for await(const e of s.receiveMessages())if(e.type===D.ASSISTANT&&e.chunk.text)yield e.chunk.text;else if(e.type===D.TASK_FINISH)break}finally{await s.disconnect()}}export{C as ApprovalMode,O as AuthenticationError,T as ConnectionError,R as HookEventType,Bt as IFlowClient,g as IFlowError,S as IFlowNotInstalledError,E as IFlowProcessError,y as JSONDecodeError,P as LogLevel,D as MessageType,v as PermissionError,_ as PermissionMode,$ as PlanPriority,N as PlanStatus,I as PortNotAvailableError,A as ProtocolError,zt as RawDataClient,L as StopReason,w as TimeoutError,G as ToolCallConfirmationOutcome,k as ToolCallConfirmationType,M as ToolCallContentType,U as ToolCallIconType,F as ToolCallStatus,x as TransportError,b as ValidationError,qt as query,Qt as queryStream};
|
|
1
|
+
import*as e from"fs";import t from"fs";import*as s from"path";import n from"path";import o from"ws";import*as i from"fs/promises";import*as r from"os";import a from"os";import*as c from"net";import*as l from"child_process";import d from"child_process";import u from"assert";import h from"events";import p from"buffer";import f from"stream";import m from"util";class g extends Error{constructor(e,t){super(e),this.name="IFlowError",this.details=t||{}}}class w extends g{constructor(e,t){super(e,t),this.name="TimeoutError"}}class S extends g{constructor(e,t){super(e,{rawData:t}),this.name="JSONDecodeError",this.rawData=t}}class y extends g{constructor(e,t){super(e,t),this.name="IFlowNotInstalledError"}}class E extends g{constructor(e,t){super(e,t),this.name="IFlowProcessError"}}class I extends g{constructor(e,t){super(e,t),this.name="PortNotAvailableError"}}class T extends g{constructor(e,t){super(e,t),this.name="ConnectionError"}}class x extends g{constructor(e,t){super(e,t),this.name="TransportError"}}class _ extends g{constructor(e,t){super(e,t),this.name="PermissionError"}}class v extends g{constructor(e,t){super(e,t),this.name="ValidationError"}}class b extends g{constructor(e,t){super(e,t),this.name="ProtocolError"}}class A extends g{constructor(e,t){super(e,t),this.name="AuthenticationError"}}var R,P,$,O,N,C,M,k,L,F,U,q,D;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(R||(R={})),function(e){e.AUTO="auto",e.MANUAL="manual",e.SELECTIVE="selective"}(P||(P={})),function(e){e.DEFAULT="default",e.AUTO_EDIT="autoEdit",e.YOLO="yolo",e.PLAN="plan"}($||($={})),function(e){e.PRE_TOOL_USE="PreToolUse",e.POST_TOOL_USE="PostToolUse",e.STOP="Stop",e.SUBAGENT_STOP="SubagentStop",e.SET_UP_ENVIRONMENT="SetUpEnvironment"}(O||(O={})),function(e){e.HIGH="high",e.MEDIUM="medium",e.LOW="low"}(N||(N={})),function(e){e.PENDING="pending",e.IN_PROGRESS="in_progress",e.COMPLETED="completed"}(C||(C={})),function(e){e.END_TURN="end_turn",e.MAX_TOKENS="max_tokens",e.REFUSAL="refusal",e.CANCELLED="cancelled"}(M||(M={})),function(e){e.PENDING="pending",e.IN_PROGRESS="in_progress",e.COMPLETED="completed",e.FAILED="failed"}(k||(k={})),function(e){e.DIFF="diff",e.MARKDOWN="markdown"}(L||(L={})),function(e){e.EDIT="edit",e.EXECUTE="execute",e.MCP="mcp",e.FETCH="fetch",e.OTHER="other"}(F||(F={})),function(e){e.ALLOW="allow",e.ALWAYS_ALLOW="alwaysAllow",e.ALWAYS_ALLOW_TOOL="alwaysAllowTool",e.ALWAYS_ALLOW_MCP_SERVER="alwaysAllowMcpServer",e.REJECT="reject"}(U||(U={})),function(e){e.URL="url",e.EMOJI="emoji"}(q||(q={})),function(e){e.PLAN="plan",e.USER="user",e.ASSISTANT="assistant",e.TOOL_CALL="tool_call",e.ERROR="error",e.TASK_FINISH="task_finish",e.ASK_USER_QUESTIONS="ask_user_questions",e.EXIT_PLAN_MODE="exit_plan_mode",e.PERMISSION_REQUEST="permission_request"}(D||(D={}));const G="2.0";var j,H,Q,W;function K(e){if(e instanceof Error){const t=e,s=t.details?.data?.details;return s?`${e.message}\n${s}`:e.message}return e?String(e):"unknown error"}!function(e){e.INITIALIZE="initialize",e.AUTHENTICATE="authenticate",e.SESSION_NEW="session/new",e.SESSION_LOAD="session/load",e.SESSION_PROMPT="session/prompt",e.SESSION_CANCEL="session/cancel",e.SESSION_SET_MODE="session/set_mode",e.SESSION_SET_MODEL="session/set_model",e.SESSION_SET_THINK="session/set_think"}(j||(j={})),function(e){e.SESSION_UPDATE="session/update",e.SESSION_REQUEST_PERMISSION="session/request_permission",e.FS_READ_TEXT_FILE="fs/read_text_file",e.FS_WRITE_TEXT_FILE="fs/write_text_file",e.PUSH_TOOL_CALL="pushToolCall",e.UPDATE_TOOL_CALL="updateToolCall",e.NOTIFY_TASK_FINISH="notifyTaskFinish",e.ASK_USER_QUESTIONS="_iflow/user/questions",e.EXIT_PLAN_MODE="_iflow/plan/exit"}(H||(H={})),function(e){e.PLAN="plan",e.TOOL_CALL="tool_call",e.TOOL_CALL_UPDATE="tool_call_update",e.USER_MESSAGE_CHUNK="user_message_chunk",e.AGENT_MESSAGE_CHUNK="agent_message_chunk",e.AGENT_THOUGHT_CHUNK="agent_thought_chunk"}(Q||(Q={})),function(e){e.ERROR="error",e.RESPONSE="response",e.FILE_READ="file_read",e.FILE_WRITE="file_write",e.SESSION_UPDATE="session_update",e.TOOL_CALL="tool_call",e.TOOL_UPDATE="tool_update",e.TASK_FINISH="task_finish",e.ASK_USER_QUESTIONS="ask_user_questions",e.EXIT_PLAN_MODE="exit_plan_mode",e.PERMISSION_REQUEST="permission_request",e.UNKNOWN="unknown"}(W||(W={}));class B{constructor(e={}){const t=e.level||"INFO";this.level=R[t]}debug(e){this.log(R.DEBUG,e)}info(e){this.log(R.INFO,e)}warn(e){this.log(R.WARN,e)}error(e,t){this.log(R.ERROR,e,t)}log(e,t,s){if(e<this.level)return;const n=`[${(new Date).toLocaleString("sv-SE").replace("T"," ")}] ${R[e]}: ${t}${s?`\n${s.stack}`:""}`;switch(e){case R.DEBUG:console.debug(n);break;case R.INFO:console.info(n);break;case R.WARN:console.warn(n);break;case R.ERROR:console.error(n)}}}const z=new B;function X(e){return!!e&&"id"in e&&"result"in e&&null!=e.result}function J(e){return!!e&&"id"in e&&"error"in e&&null!=e.error}function V(e){return!!e&&"method"in e&&!("result"in e)&&!("error"in e)}class Y{constructor(e){this.requestId=0,this.initialized=!1,this.authenticated=!1,this.pendingPermissionRequests=new Map,this.maxPendingRequests=10,this.requestTtl=300,this.logger=e.logger||z,this.transport=e.transport,this.fileHandler=e.fileHandler,this.permissionMode=e.permissionMode||P.AUTO,this.autoApproveTypes=e.autoApproveTypes||["read","fetch","list"]}nextRequestId(){return++this.requestId}checkAuthenticated(){if(!this.initialized)throw new b("Protocol not initialized. Call initialize() first.");if(!this.authenticated)throw new b("Not authenticated. Call authenticate() first.")}async sendResult(e,t){const s={jsonrpc:G,id:e,result:t};await this.transport.send(s)}async sendError(e,t,s){const n={jsonrpc:G,id:e,error:{code:t,message:s}};await this.transport.send(n)}async waitForReadySignal(){for await(const e of this.transport.receive()){const t=e.trim();if("//ready"===t){this.logger.info("Received //ready signal");break}t.startsWith("//")&&this.logger.debug(`Control message: ${t}`)}}async waitForMessageResponse(e,t,s){const{timeout:n,timeoutMsg:o=`Timeout after ${n} seconds`}=s||{},i=Date.now();for await(const s of this.transport.receive()){if(s.trim().startsWith("//")){this.logger.debug(`Control message: ${s.trim()}`);continue}let r;try{r=JSON.parse(s.trim())}catch(e){this.logger.error(`Failed to parse response: ${K(e)}`);continue}if(r.id===e){const e=t(r);if(void 0!==e)return e}if(n&&n>0&&Date.now()-i>n)throw new w(o)}}async initialize(e={}){if(this.initialized)return this.logger.warn("Protocol already initialized"),{protocolVersion:1,isAuthenticated:this.authenticated};this.logger.info("Waiting for //ready signal..."),await this.waitForReadySignal();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.INITIALIZE,params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}},...e}};await this.transport.send(s),this.logger.info("Sent initialize request");const n=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new b(`Initialize failed: ${e.error?.message}`,e.error);const t=e.result||{};return this.initialized=!0,this.authenticated=t.isAuthenticated||!1,this.logger.info(`Initialized with protocol version: ${t.protocolVersion}, authenticated: ${this.authenticated}`),t},{timeout:1e4,timeoutMsg:"Initialize timeout after 10 seconds"});if(n)return n;throw new b("Connection closed during initialization")}async authenticate(e={}){const t=e.methodId||"iflow";if(this.authenticated)return void this.logger.warn("Already authenticated");const s=this.nextRequestId(),n={jsonrpc:G,id:s,method:j.AUTHENTICATE,params:{...e,methodId:t}};await this.transport.send(n),this.logger.info(`Sent authenticate request with method: ${n.params.methodId}`);if(!await this.waitForMessageResponse(s,e=>{if("error"in e)throw new A(`Authentication failed: ${e.error?.message}`,e.error);const s=e.result||{};return s.methodId===t?(this.authenticated=!0,this.logger.info(`Authentication successful with method: ${s.methodId}`),!0):(this.authenticated=!0,this.logger.warn(`Unexpected methodId in response: ${s.methodId} (expected ${t})`),!0)},{timeout:1e4,timeoutMsg:"Authentication timeout after 10 seconds"}))throw new A("Connection closed during authentication")}async createSession(e={}){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.SESSION_NEW,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(s),this.logger.info(`Sent session/new request with cwd: ${e.cwd}`);const n=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new b(`session/new failed: ${e.error?.message}`,e.error);const t=e.result||{};if(t.sessionId)return this.logger.info(`Created session: ${t.sessionId}`),t;throw new b(`Invalid session/new response: ${JSON.stringify(t)}`)},{timeout:1e4,timeoutMsg:"Session creation timeout after 10 seconds"});if(n)return n;throw new b("Connection closed while waiting for session/new response")}async loadSession(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.SESSION_LOAD,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(s),this.logger.info(`Sent session/load request for session: ${e.sessionId}`);if(!await this.waitForMessageResponse(t,t=>{if("error"in t){if(-32601===t.error.code)throw new b("session/load is not supported by the current iFlow version. Use session/new to create a new session instead.",t.error);throw new b(`session/load failed: ${t.error?.message}`,t.error)}return this.logger.info(`Session loaded successfully: ${e.sessionId}`),!0},{timeout:1e4,timeoutMsg:"Session load timeout after 10 seconds"}))throw new b("Connection closed while waiting for session/load response")}async sendPrompt(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.SESSION_PROMPT,params:e};return await this.transport.send(s),this.logger.info(`Sent prompt with ${e.prompt.length} content blocks`),t}async cancelSession(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.SESSION_CANCEL,params:e};await this.transport.send(s),this.logger.info("Sent session/cancel request")}async setMode(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.SESSION_SET_MODE,params:e};await this.transport.send(s),this.logger.info(`Sent session/set_mode request with modeId: ${e.modeId}`);try{const e=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new b(`session/set_mode failed: ${e.error?.message}`,e.error);return e.result},{timeout:1e4,timeoutMsg:"Set mode timeout after 10 seconds"});if(!e?.success)throw new b("session/set_mode failed: operation unsuccessful");return e.currentModeId}catch(t){throw this.logger.error(`Failed to set mode to ${e.modeId}: ${K(t)}`),t}}async setModel(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.SESSION_SET_MODEL,params:e};await this.transport.send(s),this.logger.info(`Sent session/set_model request with modelId: ${e.modelId}`);try{const e=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new b(`session/set_model failed: ${e.error?.message}`,e.error);return e.result},{timeout:1e4,timeoutMsg:"Set model timeout after 10 seconds"});if(!e?.success)throw new b("session/set_model failed: operation unsuccessful");return e.currentModelId}catch(t){throw this.logger.error(`Failed to set model to ${e.modelId}: ${K(t)}`),t}}async setThink(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:G,id:t,method:j.SESSION_SET_THINK,params:e};await this.transport.send(s),this.logger.info(`Sent session/set_think request with thinkEnabled: ${e.thinkEnabled}, thinkConfig: ${e.thinkConfig||"default"}`);try{const e=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new b(`session/set_think failed: ${e.error?.message}`,e.error);return e.result},{timeout:1e4,timeoutMsg:"Set think timeout after 10 seconds"});if(!e?.success)throw new b("session/set_think failed: operation unsuccessful");return e}catch(e){throw this.logger.error(`Failed to set think: ${K(e)}`),e}}async respondToAskUserQuestions(e,t){const s={answers:t};await this.sendResult(e,s),this.logger.info(`Sent ask_user_questions response with ${Object.keys(t).length} answers`)}async respondToExitPlanMode(e,t){const s={approved:t};await this.sendResult(e,s),this.logger.info("Sent exit_plan_mode response: "+(t?"approved":"rejected"))}async sendPermissionResponse(e,t){if(!this.pendingPermissionRequests.has(e))throw new Error(`Unknown permission request: ${e}`);const s={outcome:{outcome:"selected",optionId:t}};try{await this.sendResult(e,s),this.pendingPermissionRequests.delete(e),this.logger.info(`Sent permission response for request ${e}: ${t}`)}catch(t){throw this.logger.error(`Failed to send permission response for request ${e}: ${K(t)}`),t}}async cancelPermissionResponse(e){if(!this.pendingPermissionRequests.has(e))throw new Error(`Unknown permission request: ${e}`);const t={outcome:{outcome:"cancelled"}};try{await this.sendResult(e,t),this.pendingPermissionRequests.delete(e),this.logger.info(`Cancelled permission request: ${e}`)}catch(t){throw this.logger.error(`Failed to cancel permission request ${e}: ${K(t)}`),t}}async*handleMessages(){for await(const e of this.transport.receive()){if(e.trim().startsWith("//")){this.logger.debug(`Control message: ${e.trim()}`);continue}let t;try{t=JSON.parse(e.trim())}catch(t){throw this.logger.error(`Failed to parse message: ${K(t)}`),new S("Invalid JSON received",e)}if(V(t)){const e=await this.handleClientMessage(t);yield e}else X(t)?yield{type:"response",id:t.id,result:t.result}:J(t)&&(yield{type:"error",code:t.error.code,error:`${t.error.message}, detail: ${t.error.data?.details||"unknown"}`})}}async handleClientMessage(e){const{method:t}=e;switch(t){case H.FS_READ_TEXT_FILE:return await this.handleReadTextFile(e);case H.FS_WRITE_TEXT_FILE:return await this.handleWriteTextFile(e);case H.SESSION_UPDATE:return await this.handleSessionUpdate(e);case H.SESSION_REQUEST_PERMISSION:return await this.handleRequestPermission(e);case H.PUSH_TOOL_CALL:return await this.handlePushToolCall(e);case H.UPDATE_TOOL_CALL:return await this.handleUpdateToolCall(e);case H.NOTIFY_TASK_FINISH:return await this.handleNotifyTaskFinish(e);case H.ASK_USER_QUESTIONS:return await this.handleAskUserQuestions(e);case H.EXIT_PLAN_MODE:return await this.handleExitPlanMode(e);default:return await this.handleUnknownMessage(e)}}async handleReadTextFile(e){const{id:t,method:s,params:n}=e,{path:o,limit:i,line:r}=n||{};let a;if(this.logger.info(`fs/read_text_file request for: ${o}`),!this.fileHandler){const e="File system access not configured";return void 0!==t&&await this.sendError(t,-32603,e),{type:"error",code:-32603,error:e,method:s}}try{a=await this.fileHandler.readFile(o,r,i)}catch(e){const n=K(e);return this.logger.error(`Error reading file ${o}: ${n}`),void 0!==t&&await this.sendError(t,-32603,n),{type:"error",code:-32603,error:n,method:s}}return void 0!==t&&await this.sendResult(t,{content:a}),{type:"file_read",path:o,content:a}}async handleWriteTextFile(e){const{id:t,method:s,params:n}=e,{path:o,content:i}=n||{};if(this.logger.info(`fs/write_text_file request for: ${o}`),!this.fileHandler){const e="File system access not configured";return void 0!==t&&await this.sendError(t,-32603,e),{type:"error",code:-32603,error:e,method:s}}try{await this.fileHandler.writeFile(o,i)}catch(e){const n=K(e);return this.logger.error(`Error writing file ${o}: ${n}`),void 0!==t&&await this.sendError(t,-32603,n),{type:"error",code:-32603,error:n,method:s}}return void 0!==t&&await this.sendResult(t,{success:!0}),{type:"file_write",path:o,content:i}}async handleSessionUpdate(e){const{params:t}=e,{sessionId:s,update:n}=t;return{type:"session_update",sessionId:s,updateData:n}}async handleRequestPermission(e){const{id:t,params:s}=e,n=s.toolCall||{},o=s.options||[],i=s.sessionId;return void 0!==t?this.pendingPermissionRequests.size>=this.maxPendingRequests?(this.logger.error(`Max pending permission requests limit reached (${this.maxPendingRequests}). Rejecting new request to prevent memory leak.`),await this.sendError(t,-32e3,`Too many pending requests (${this.maxPendingRequests})`),{type:"error",code:-32e3,error:`Too many pending requests (${this.maxPendingRequests})`,method:"session/request_permission"}):(this.pendingPermissionRequests.set(t,{created_at:Date.now(),ttl:this.requestTtl,toolCall:n,options:o}),this.logger.info(`Received permission request for tool '${n.title||"unknown"}', waiting for user response (pending: ${this.pendingPermissionRequests.size}/${this.maxPendingRequests})`),{type:W.PERMISSION_REQUEST,requestId:t,sessionId:i,toolCall:n,options:o,needsUserResponse:!0}):(this.logger.error("Permission request without request_id - cannot track response"),{type:"error",code:-32600,error:"Permission request without request_id - cannot track response",method:"session/request_permission"})}async handlePushToolCall(e){const{id:t,params:s}=e,n=`tool_${this.nextRequestId()}`,o={id:n};return void 0!==t&&await this.sendResult(t,o),{type:"tool_call",id:n,params:s}}async handleUpdateToolCall(e){const{id:t,params:s}=e;return void 0!==t&&await this.sendResult(t,null),{type:"tool_update",params:s}}async handleNotifyTaskFinish(e){const{id:t,params:s}=e;return void 0!==t&&await this.sendResult(t,null),{type:"task_finish",params:s}}async handleAskUserQuestions(e){const{id:t,params:s}=e;return this.logger.info(`ask_user_questions request with ${s?.questions?.length||0} questions`),{type:"ask_user_questions",requestId:t,params:s}}async handleExitPlanMode(e){const{id:t,params:s}=e;return this.logger.info(`exit_plan_mode request with plan: ${s?.plan?.substring(0,50)}...`),{type:"exit_plan_mode",requestId:t,params:s}}async handleUnknownMessage(e){const{id:t,method:s,params:n}=e;return this.logger.warn(`Unknown method: ${s}`),void 0!==t&&await this.sendError(t,-32601,"Method not found"),{type:"unknown",method:s,params:n}}}class Z{constructor(e){this.ws=null,this.connected=!1,this.url=e.url,this.logger=e.logger||z,this.timeout=e.timeout||3e5}get isConnected(){return!!this.ws&&this.connected}checkConnected(){if(!this.isConnected)throw new T("Not connected")}async connect(){if(this.connected)this.logger.warn(`Already connected to ${this.url}`);else try{this.logger.info(`Connecting to ${this.url}`),this.ws=await new Promise((e,t)=>{const s=new o(this.url),n=setTimeout(()=>{s.close(),t(new w(`Connected to ${this.url} timeout after ${this.timeout/1e3}s`))},this.timeout);s.on("open",()=>{clearTimeout(n),this.connected=!0,this.logger.info(`Connected to ${this.url} succesfully`),e(s)}),s.on("error",e=>{clearTimeout(n),this.connected=!1,t(e)}),s.on("close",(e,s)=>{clearTimeout(n),this.connected=!1,t(new Error(`${s} (code: ${e})`))})})}catch(e){if(e instanceof w)throw e;throw new T(`Failed to connect to ${this.url}: ${K(e)}`)}}async close(){if(this.ws&&this.connected)try{this.ws.close(),this.logger.info("Connection closed")}catch(e){this.logger.warn(`Error closing connection: ${K(e)}`)}this.ws=null,this.connected=!1}async send(e){this.checkConnected();try{const t="string"==typeof e?e:JSON.stringify(e);await new Promise((e,s)=>{this.ws.send(t,n=>{n?s(n):(this.logger.debug(`Sent message: ${t}`),e())})})}catch(e){throw this.connected=!1,new x(`Failed to send message: ${K(e)}`)}}async*receive(){for(this.checkConnected();this.isConnected;)try{const e=await this.receiveRawData();this.logger.debug(`Received message: ${e}`),yield e}catch(e){if(this.connected=!1,e instanceof T&&e.details.isClosed){this.logger.info("Connection closed");break}throw new x(`Failed to receive message: ${K(e)}`)}}receiveRawData(){return new Promise((e,t)=>{if(!this.isConnected)return void t(new T("Not connected"));const s=()=>{this.ws&&(this.ws.off("close",n),this.ws.off("error",o),this.ws.off("message",i))},n=()=>{s(),this.connected=!1,t(new T("Connection closed",{isClosed:!0}))},o=e=>{s(),this.connected=!1,t(e)},i=t=>{s(),e(t.toString())};this.ws&&(this.ws.on("close",n),this.ws.on("error",o),this.ws.on("message",i))})}}class ee{constructor(e={}){this.cwd=e.cwd||process.cwd(),this.logger=e.logger||z,this.readOnly=e.readOnly||!1,this.maxFileSize=e.maxFileSize||10485760,e.allowedDirs?this.allowedDirs=new Set(e.allowedDirs.map(e=>s.resolve(this.cwd,e))):this.allowedDirs=new Set([this.cwd]),this.logger.info(`File handler initialized with ${this.allowedDirs.size} allowed directories`);for(const e of this.allowedDirs)this.logger.debug(` Allowed: ${e}`)}isPathAllowed(e){try{const t=s.resolve(this.cwd,e);for(const e of this.allowedDirs)if(t.startsWith(e))return!0;return this.logger.warn(`Path not in allowed directories: ${t}`),!1}catch(e){return e instanceof Error&&this.logger.error(`Error checking path: ${e.message}`,e),!1}}async readFile(t,n,o){if(!this.isPathAllowed(t))throw new _(`Access denied: ${t}`);const r=s.resolve(this.cwd,t);try{if(!e.existsSync(r))throw new v(`File not found: ${t}`);try{await i.access(r,e.constants.R_OK)}catch{throw new _(`Permission denied: ${t}`)}const s=await i.stat(r);if(!s.isFile())throw new v(`Not a file: ${t}`);if(s.size>this.maxFileSize)throw new v(`File too large: ${s.size} bytes (max: ${this.maxFileSize})`);const a=await i.readFile(r,"utf-8");if(void 0!==n||void 0!==o){const e=a.split("\n"),s=n?n-1:0,i=o?s+o:e.length,r=Math.max(0,s),c=Math.min(e.length,i);return this.logger.debug(`Read ${c-r} lines from ${t}`),e.slice(r,c).join("\n")}return this.logger.debug(`Read ${a.length} bytes from ${t}`),a}catch(e){if(e instanceof v||e instanceof _)throw e;throw new v(`Failed to read file: ${K(e)}`)}}async writeFile(e,t){if(this.readOnly)throw new _("File system is in read-only mode");if(!this.isPathAllowed(e))throw new _(`Access denied: ${e}`);const n=s.resolve(this.cwd,e);try{await i.mkdir(s.dirname(n),{recursive:!0}),await i.writeFile(n,t,"utf-8"),this.logger.debug(`Wrote ${t.length} bytes to ${e}`)}catch(e){throw new v(`Failed to write file: ${K(e)}`)}}async addAllowedDir(t){const n=s.resolve(this.cwd,t);try{if(!e.existsSync(n))throw new v(`Directory does not exist: ${n}`);if(!(await i.stat(n)).isDirectory())throw new v(`Not a directory: ${n}`);this.allowedDirs.add(n),this.logger.info(`Added allowed directory: ${n}`)}catch(e){if(e instanceof v)throw e;throw new v(`Failed to add ${n} as allowed directory: ${K(e)}`)}}removeAllowedDir(e){const t=s.resolve(this.cwd,e);this.allowedDirs.delete(t),this.logger.info(`Removed allowed directory: ${t}`)}}var te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function se(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ne,oe,ie,re,ae,ce,le,de,ue={exports:{}},he={exports:{}};function pe(){if(oe)return ne;oe=1,ne=n,n.sync=function(t,n){return s(e.statSync(t),t,n)};var e=t;function s(e,t,s){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var s=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!s)return!0;if(-1!==(s=s.split(";")).indexOf(""))return!0;for(var n=0;n<s.length;n++){var o=s[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,s)}function n(t,n,o){e.stat(t,function(e,i){o(e,!e&&s(i,t,n))})}return ne}function fe(){if(re)return ie;re=1,ie=s,s.sync=function(t,s){return n(e.statSync(t),s)};var e=t;function s(t,s,o){e.stat(t,function(e,t){o(e,!e&&n(t,s))})}function n(e,t){return e.isFile()&&function(e,t){var s=e.mode,n=e.uid,o=e.gid,i=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),r=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),d=a|c;return s&l||s&c&&o===r||s&a&&n===i||s&d&&0===i}(e,t)}return ie}function me(){if(de)return le;de=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=n,s=e?";":":",o=function(){if(ce)return ae;var e;function t(s,n,o){if("function"==typeof n&&(o=n,n={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,o){t(s,n||{},function(t,s){t?o(t):e(s)})})}e(s,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),o(e,t)})}return ce=1,e="win32"===process.platform||te.TESTING_WINDOWS?pe():fe(),ae=t,t.sync=function(t,s){try{return e.sync(t,s||{})}catch(e){if(s&&s.ignoreErrors||"EACCES"===e.code)return!1;throw e}},ae}(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),r=(t,n)=>{const o=n.colon||s,i=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(o)],r=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?r.split(o):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:i,pathExt:a,pathExtExe:r}},a=(e,s,n)=>{"function"==typeof s&&(n=s,s={}),s||(s={});const{pathEnv:a,pathExt:c,pathExtExe:l}=r(e,s),d=[],u=n=>new Promise((o,r)=>{if(n===a.length)return s.all&&d.length?o(d):r(i(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=t.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;o(h(p,n,0))}),h=(e,t,n)=>new Promise((i,r)=>{if(n===c.length)return i(u(t+1));const a=c[n];o(e+a,{pathExt:l},(o,r)=>{if(!o&&r){if(!s.all)return i(e+a);d.push(e+a)}return i(h(e,t,n+1))})});return n?u(0).then(e=>n(null,e),n):u(0)};return le=a,a.sync=(e,s)=>{s=s||{};const{pathEnv:n,pathExt:a,pathExtExe:c}=r(e,s),l=[];for(let i=0;i<n.length;i++){const r=n[i],d=/^".*"$/.test(r)?r.slice(1,-1):r,u=t.join(d,e),h=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<a.length;e++){const t=h+a[e];try{if(o.sync(t,{pathExt:c})){if(!s.all)return t;l.push(t)}}catch(e){}}}if(s.all&&l.length)return l;if(s.nothrow)return null;throw i(e)},le}var ge,we,Se,ye={exports:{}};function Ee(){if(ge)return ye.exports;ge=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return ye.exports=e,ye.exports.default=e,ye.exports}var Ie,Te,xe,_e,ve,be,Ae,Re,Pe,$e,Oe,Ne,Ce,Me,ke={};function Le(){return xe?Te:(xe=1,Te=/^#!(.*)/)}function Fe(){if(ve)return _e;ve=1;const e=Le();return _e=(t="")=>{const s=t.match(e);if(!s)return null;const[n,o]=s[0].replace(/#! ?/,"").split(" "),i=n.split("/").pop();return"env"===i?o:o?`${i} ${o}`:i},_e}function Ue(){if(Pe)return Re;Pe=1;const e=n,s=function(){if(Se)return we;Se=1;const e=n,t=me(),s=Ee();function o(n,o){const i=n.options.env||process.env,r=process.cwd(),a=null!=n.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(n.options.cwd)}catch(e){}let l;try{l=t.sync(n.command,{path:i[s({env:i})],pathExt:o?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(r)}return l&&(l=e.resolve(a?n.options.cwd:"",l)),l}return we=function(e){return o(e)||o(e,!0)}}(),o=function(){if(Ie)return ke;Ie=1;const e=/([()\][%!^"`<>&|;, *?])/g;return ke.command=function(t){return t.replace(e,"^$1")},ke.argument=function(t,s){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),s&&(t=t.replace(e,"^$1")),t},ke}(),i=function(){if(Ae)return be;Ae=1;const e=t,s=Fe();return be=function(t){const n=Buffer.alloc(150);let o;try{o=e.openSync(t,"r"),e.readSync(o,n,0,150,0),e.closeSync(o)}catch(e){}return s(n.toString())},be}(),r="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(t){if(!r)return t;const n=function(e){e.file=s(e);const t=e.file&&i(e.file);return t?(e.args.unshift(e.file),e.command=t,s(e)):e.file}(t),l=!a.test(n);if(t.options.forceShell||l){const s=c.test(n);t.command=e.normalize(t.command),t.command=o.command(t.command),t.args=t.args.map(e=>o.argument(e,s));const i=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${i}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}return Re=function(e,t,s){t&&!Array.isArray(t)&&(s=t,t=null);const n={command:e,args:t=t?t.slice(0):[],options:s=Object.assign({},s),file:void 0,original:{command:e,args:t}};return s.shell?n:l(n)},Re}function qe(){if(Oe)return $e;Oe=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function s(s,n){return e&&1===s&&!n.file?t(n.original,"spawn"):null}return $e={hookChildProcess:function(t,n){if(!e)return;const o=t.emit;t.emit=function(e,i){if("exit"===e){const e=s(i,n);if(e)return o.call(t,"error",e)}return o.apply(t,arguments)}},verifyENOENT:s,verifyENOENTSync:function(s,n){return e&&1===s&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},$e}function De(){if(Ne)return he.exports;Ne=1;const e=d,t=Ue(),s=qe();function n(n,o,i){const r=t(n,o,i),a=e.spawn(r.command,r.args,r.options);return s.hookChildProcess(a,r),a}return he.exports=n,he.exports.spawn=n,he.exports.sync=function(n,o,i){const r=t(n,o,i),a=e.spawnSync(r.command,r.args,r.options);return a.error=a.error||s.verifyENOENTSync(a.status,r),a},he.exports._parse=t,he.exports._enoent=s,he.exports}function Ge(){return Me?Ce:(Me=1,Ce=e=>{const t="string"==typeof e?"\n":"\n".charCodeAt(),s="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,e.length-1)),e[e.length-1]===s&&(e=e.slice(0,e.length-1)),e})}var je,He={exports:{}};function Qe(){return je||(je=1,function(e){const t=n,s=Ee(),o=e=>{let n;e={cwd:process.cwd(),path:process.env[s()],execPath:process.execPath,...e};let o=t.resolve(e.cwd);const i=[];for(;n!==o;)i.push(t.join(o,"node_modules/.bin")),n=o,o=t.resolve(o,"..");const r=t.resolve(e.cwd,e.execPath,"..");return i.push(r),i.concat(e.path).join(t.delimiter)};e.exports=o,e.exports.default=o,e.exports.env=t=>{const n={...(t={env:process.env,...t}).env},o=s({env:n});return t.path=n[o],n[o]=e.exports(t),n}}(He)),He.exports}var We,Ke,Be={exports:{}},ze={exports:{}};function Xe(){if(We)return ze.exports;We=1;const e=(e,t)=>{for(const s of Reflect.ownKeys(t))Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(t,s));return e};return ze.exports=e,ze.exports.default=e,ze.exports}function Je(){if(Ke)return Be.exports;Ke=1;const e=Xe(),t=new WeakMap,s=(s,n={})=>{if("function"!=typeof s)throw new TypeError("Expected a function");let o,i=0;const r=s.displayName||s.name||"<anonymous>",a=function(...e){if(t.set(a,++i),1===i)o=s.apply(this,e),s=null;else if(!0===n.throw)throw new Error(`Function \`${r}\` can only be called once`);return o};return e(a,s),t.set(a,i),a};return Be.exports=s,Be.exports.default=s,Be.exports.callCount=e=>{if(!t.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return t.get(e)},Be.exports}var Ve,Ye={},Ze={},et={};var tt,st,nt,ot,it,rt={};function at(){if(tt)return rt;tt=1,Object.defineProperty(rt,"__esModule",{value:!0}),rt.SIGRTMAX=rt.getRealtimeSignals=void 0;rt.getRealtimeSignals=function(){const n=s-t+1;return Array.from({length:n},e)};const e=function(e,s){return{name:`SIGRT${s+1}`,number:t+s,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},t=34,s=64;return rt.SIGRTMAX=s,rt}function ct(){if(st)return Ze;st=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.getSignals=void 0;var e=a,t=(Ve||(Ve=1,Object.defineProperty(et,"__esModule",{value:!0}),et.SIGNALS=void 0,et.SIGNALS=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}]),et),s=at();Ze.getSignals=function(){const e=(0,s.getRealtimeSignals)();return[...t.SIGNALS,...e].map(n)};const n=function({name:t,number:s,description:n,action:o,forced:i=!1,standard:r}){const{signals:{[t]:a}}=e.constants,c=void 0!==a;return{name:t,number:c?a:s,description:n,supported:c,action:o,forced:i,standard:r}};return Ze}function lt(){if(it)return ot;it=1;const{signalsByName:e}=function(){if(nt)return Ye;nt=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.signalsByNumber=Ye.signalsByName=void 0;var e=a,t=ct(),s=at();const n=function(e,{name:t,number:s,description:n,supported:o,action:i,forced:r,standard:a}){return{...e,[t]:{name:t,number:s,description:n,supported:o,action:i,forced:r,standard:a}}},o=(0,t.getSignals)().reduce(n,{});Ye.signalsByName=o;const i=function(e,t){const s=r(e,t);if(void 0===s)return{};const{name:n,description:o,supported:i,action:a,forced:c,standard:l}=s;return{[e]:{name:n,number:e,description:o,supported:i,action:a,forced:c,standard:l}}},r=function(t,s){const n=s.find(({name:s})=>e.constants.signals[s]===t);return void 0!==n?n:s.find(e=>e.number===t)},c=function(){const e=(0,t.getSignals)(),n=s.SIGRTMAX+1,o=Array.from({length:n},(t,s)=>i(s,e));return Object.assign({},...o)}();return Ye.signalsByNumber=c,Ye}();return ot=({stdout:t,stderr:s,all:n,error:o,signal:i,exitCode:r,command:a,escapedCommand:c,timedOut:l,isCanceled:d,killed:u,parsed:{options:{timeout:h}}})=>{r=null===r?void 0:r;const p=void 0===(i=null===i?void 0:i)?void 0:e[i].description,f=(({timedOut:e,timeout:t,errorCode:s,signal:n,signalDescription:o,exitCode:i,isCanceled:r})=>e?`timed out after ${t} milliseconds`:r?"was canceled":void 0!==s?`failed with ${s}`:void 0!==n?`was killed with ${n} (${o})`:void 0!==i?`failed with exit code ${i}`:"failed")({timedOut:l,timeout:h,errorCode:o&&o.code,signal:i,signalDescription:p,exitCode:r,isCanceled:d}),m=`Command ${f}: ${a}`,g="[object Error]"===Object.prototype.toString.call(o),w=g?`${m}\n${o.message}`:m,S=[w,s,t].filter(Boolean).join("\n");return g?(o.originalMessage=o.message,o.message=S):o=new Error(S),o.shortMessage=w,o.command=a,o.escapedCommand=c,o.exitCode=r,o.signal=i,o.signalDescription=p,o.stdout=t,o.stderr=s,void 0!==n&&(o.all=n),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=Boolean(l),o.isCanceled=d,o.killed=u&&!l,o},ot}var dt,ut={exports:{}};function ht(){if(dt)return ut.exports;dt=1;const e=["stdin","stdout","stderr"],t=t=>{if(!t)return;const{stdio:s}=t;if(void 0===s)return e.map(e=>t[e]);if((t=>e.some(e=>void 0!==t[e]))(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${e.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof s)return s;if(!Array.isArray(s))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof s}\``);const n=Math.max(s.length,e.length);return Array.from({length:n},(e,t)=>s[t])};return ut.exports=t,ut.exports.node=e=>{const s=t(e);return"ipc"===s?"ipc":void 0===s||"string"==typeof s?[s,s,s,"ipc"]:s.includes("ipc")?s:[...s,"ipc"]},ut.exports}var pt,ft,mt,gt,wt,St,yt={exports:{}},Et={exports:{}};function It(){return pt||(pt=1,(e=Et).exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],"win32"!==process.platform&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")),Et.exports;var e}function Tt(){if(gt)return mt;gt=1;const e=a,t=function(){if(ft)return yt.exports;ft=1;var e=te.process;const t=function(e){return e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on};if(t(e)){var s,n=u,o=It(),i=/^win/i.test(e.platform),r=h;"function"!=typeof r&&(r=r.EventEmitter),e.__signal_exit_emitter__?s=e.__signal_exit_emitter__:((s=e.__signal_exit_emitter__=new r).count=0,s.emitted={}),s.infinite||(s.setMaxListeners(1/0),s.infinite=!0),yt.exports=function(e,o){if(!t(te.process))return function(){};n.equal(typeof e,"function","a callback must be provided for exit handler"),!1===d&&p();var i="exit";return o&&o.alwaysLast&&(i="afterexit"),s.on(i,e),function(){s.removeListener(i,e),0===s.listeners("exit").length&&0===s.listeners("afterexit").length&&a()}};var a=function(){d&&t(te.process)&&(d=!1,o.forEach(function(t){try{e.removeListener(t,l[t])}catch(e){}}),e.emit=g,e.reallyExit=f,s.count-=1)};yt.exports.unload=a;var c=function(e,t,n){s.emitted[e]||(s.emitted[e]=!0,s.emit(e,t,n))},l={};o.forEach(function(n){l[n]=function(){t(te.process)&&e.listeners(n).length===s.count&&(a(),c("exit",null,n),c("afterexit",null,n),i&&"SIGHUP"===n&&(n="SIGINT"),e.kill(e.pid,n))}}),yt.exports.signals=function(){return o};var d=!1,p=function(){!d&&t(te.process)&&(d=!0,s.count+=1,o=o.filter(function(t){try{return e.on(t,l[t]),!0}catch(e){return!1}}),e.emit=w,e.reallyExit=m)};yt.exports.load=p;var f=e.reallyExit,m=function(s){t(te.process)&&(e.exitCode=s||0,c("exit",e.exitCode,null),c("afterexit",e.exitCode,null),f.call(e,e.exitCode))},g=e.emit,w=function(s,n){if("exit"===s&&t(te.process)){void 0!==n&&(e.exitCode=n);var o=g.apply(this,arguments);return c("exit",e.exitCode,null),c("afterexit",e.exitCode,null),o}return g.apply(this,arguments)}}else yt.exports=function(){return function(){}};return yt.exports}(),s=(e,t,s,o)=>{if(!n(t,s,o))return;const r=i(s),a=setTimeout(()=>{e("SIGKILL")},r);a.unref&&a.unref()},n=(e,{forceKillAfterTimeout:t},s)=>o(e)&&!1!==t&&s,o=t=>t===e.constants.signals.SIGTERM||"string"==typeof t&&"SIGTERM"===t.toUpperCase(),i=({forceKillAfterTimeout:e=!0})=>{if(!0===e)return 5e3;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e};return mt={spawnedKill:(e,t="SIGTERM",n={})=>{const o=e(t);return s(e,t,n,o),o},spawnedCancel:(e,t)=>{e.kill()&&(t.isCanceled=!0)},setupTimeout:(e,{timeout:t,killSignal:s="SIGTERM"},n)=>{if(0===t||void 0===t)return n;let o;const i=new Promise((n,i)=>{o=setTimeout(()=>{((e,t,s)=>{e.kill(t),s(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))})(e,s,i)},t)}),r=n.finally(()=>{clearTimeout(o)});return Promise.race([i,r])},validateTimeout:({timeout:e})=>{if(void 0!==e&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},setExitHandler:async(e,{cleanup:s,detached:n},o)=>{if(!s||n)return o;const i=t(()=>{e.kill()});return o.finally(()=>{i()})}}}var xt,_t,vt,bt,At,Rt,Pt,$t,Ot,Nt,Ct,Mt,kt={exports:{}};function Lt(){if(_t)return xt;_t=1;const{PassThrough:e}=f;return xt=t=>{t={...t};const{array:s}=t;let{encoding:n}=t;const o="buffer"===n;let i=!1;s?i=!(n||o):n=n||"utf8",o&&(n=null);const r=new e({objectMode:i});n&&r.setEncoding(n);let a=0;const c=[];return r.on("data",e=>{c.push(e),i?a=c.length:a+=e.length}),r.getBufferedValue=()=>s?c:o?Buffer.concat(c,a):c.join(""),r.getBufferedLength=()=>a,r},xt}function Ft(){if(vt)return kt.exports;vt=1;const{constants:e}=p,t=f,{promisify:s}=m,n=Lt(),o=s(t.pipeline);class i extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function r(t,s){if(!t)throw new Error("Expected a stream");s={maxBuffer:1/0,...s};const{maxBuffer:r}=s,a=n(s);return await new Promise((s,n)=>{const c=t=>{t&&a.getBufferedLength()<=e.MAX_LENGTH&&(t.bufferedData=a.getBufferedValue()),n(t)};(async()=>{try{await o(t,a),s()}catch(e){c(e)}})(),a.on("data",()=>{a.getBufferedLength()>r&&c(new i)})}),a.getBufferedValue()}return kt.exports=r,kt.exports.buffer=(e,t)=>r(e,{...t,encoding:"buffer"}),kt.exports.array=(e,t)=>r(e,{...t,array:!0}),kt.exports.MaxBufferError=i,kt.exports}function Ut(){if(At)return bt;At=1;const{PassThrough:e}=f;return bt=function(){var t=[],s=new e({objectMode:!0});return s.setMaxListeners(0),s.add=n,s.isEmpty=function(){return 0==t.length},s.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(n),s;function n(e){return Array.isArray(e)?(e.forEach(n),this):(t.push(e),e.once("end",o.bind(null,e)),e.once("error",s.emit.bind(s,"error")),e.pipe(s,{end:!1}),this)}function o(e){!(t=t.filter(function(t){return t!==e})).length&&s.readable&&s.end()}},bt}function qt(){if(Pt)return Rt;Pt=1;const e=function(){if(St)return wt;St=1;const e=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;return e.writable=t=>e(t)&&!1!==t.writable&&"function"==typeof t._write&&"object"==typeof t._writableState,e.readable=t=>e(t)&&!1!==t.readable&&"function"==typeof t._read&&"object"==typeof t._readableState,e.duplex=t=>e.writable(t)&&e.readable(t),e.transform=t=>e.duplex(t)&&"function"==typeof t._transform,wt=e}(),t=Ft(),s=Ut(),n=async(e,t)=>{if(e){e.destroy();try{return await t}catch(e){return e.bufferedData}}},o=(e,{encoding:s,buffer:n,maxBuffer:o})=>{if(e&&n)return s?t(e,{encoding:s,maxBuffer:o}):t.buffer(e,{maxBuffer:o})};return Rt={handleInput:(t,s)=>{void 0!==s&&void 0!==t.stdin&&(e(s)?s.pipe(t.stdin):t.stdin.end(s))},makeAllStream:(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=s();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},getSpawnedResult:async({stdout:e,stderr:t,all:s},{encoding:i,buffer:r,maxBuffer:a},c)=>{const l=o(e,{encoding:i,buffer:r,maxBuffer:a}),d=o(t,{encoding:i,buffer:r,maxBuffer:a}),u=o(s,{encoding:i,buffer:r,maxBuffer:2*a});try{return await Promise.all([c,l,d,u])}catch(o){return Promise.all([{error:o,signal:o.signal,timedOut:o.timedOut},n(e,l),n(t,d),n(s,u)])}},validateInputSync:({input:t})=>{if(e(t))throw new TypeError("The `input` option cannot be a stream in sync mode")}},Rt}function Dt(){if(Ct)return Nt;Ct=1;const e=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],t=/^[\w.-]+$/,s=/"/g,n=/ +/g;return Nt={joinCommand:(t,s)=>e(t,s).join(" "),getEscapedCommand:(n,o)=>e(n,o).map(e=>(e=>"string"!=typeof e||t.test(e)?e:`"${e.replace(s,'\\"')}"`)(e)).join(" "),parseCommand:e=>{const t=[];for(const s of e.trim().split(n)){const e=t[t.length-1];e&&e.endsWith("\\")?t[t.length-1]=`${e.slice(0,-1)} ${s}`:t.push(s)}return t}}}var Gt=function(){if(Mt)return ue.exports;Mt=1;const e=n,t=d,s=De(),o=Ge(),i=Qe(),r=Je(),a=lt(),c=ht(),{spawnedKill:l,spawnedCancel:u,setupTimeout:h,validateTimeout:p,setExitHandler:f}=Tt(),{handleInput:m,getSpawnedResult:g,makeAllStream:w,validateInputSync:S}=qt(),{mergePromise:y,getSpawnedPromise:E}=function(){if(Ot)return $t;Ot=1;const e=(async()=>{})().constructor.prototype,t=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(e,t)]);return $t={mergePromise:(e,s)=>{for(const[n,o]of t){const t="function"==typeof s?(...e)=>Reflect.apply(o.value,s(),e):o.value.bind(s);Reflect.defineProperty(e,n,{...o,value:t})}return e},getSpawnedPromise:e=>new Promise((t,s)=>{e.on("exit",(e,s)=>{t({exitCode:e,signal:s})}),e.on("error",e=>{s(e)}),e.stdin&&e.stdin.on("error",e=>{s(e)})})},$t}(),{joinCommand:I,parseCommand:T,getEscapedCommand:x}=Dt(),_=(t,n,o={})=>{const r=s._parse(t,n,o);return t=r.command,n=r.args,(o={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(o=r.options).cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...o}).env=(({env:e,extendEnv:t,preferLocal:s,localDir:n,execPath:o})=>{const r=t?{...process.env,...e}:e;return s?i.env({env:r,cwd:n,execPath:o}):r})(o),o.stdio=c(o),"win32"===process.platform&&"cmd"===e.basename(t,".exe")&&n.unshift("/q"),{file:t,args:n,options:o,parsed:r}},v=(e,t,s)=>"string"==typeof t||Buffer.isBuffer(t)?e.stripFinalNewline?o(t):t:void 0===s?void 0:"",b=(e,s,n)=>{const o=_(e,s,n),i=I(e,s),c=x(e,s);let d;p(o.options);try{d=t.spawn(o.file,o.args,o.options)}catch(e){const s=new t.ChildProcess,n=Promise.reject(a({error:e,stdout:"",stderr:"",all:"",command:i,escapedCommand:c,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return y(s,n)}const S=E(d),T=h(d,o.options,S),b=f(d,o.options,T),A={isCanceled:!1};d.kill=l.bind(null,d.kill.bind(d)),d.cancel=u.bind(null,d,A);const R=r(async()=>{const[{error:e,exitCode:t,signal:s,timedOut:n},r,l,u]=await g(d,o.options,b),h=v(o.options,r),p=v(o.options,l),f=v(o.options,u);if(e||0!==t||null!==s){const r=a({error:e,exitCode:t,signal:s,stdout:h,stderr:p,all:f,command:i,escapedCommand:c,parsed:o,timedOut:n,isCanceled:A.isCanceled,killed:d.killed});if(!o.options.reject)return r;throw r}return{command:i,escapedCommand:c,exitCode:0,stdout:h,stderr:p,all:f,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return m(d,o.options.input),d.all=w(d,o.options),y(d,R)};return ue.exports=b,ue.exports.sync=(e,s,n)=>{const o=_(e,s,n),i=I(e,s),r=x(e,s);let c;S(o.options);try{c=t.spawnSync(o.file,o.args,o.options)}catch(e){throw a({error:e,stdout:"",stderr:"",all:"",command:i,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const l=v(o.options,c.stdout,c.error),d=v(o.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=a({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:i,escapedCommand:r,parsed:o,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!o.options.reject)return e;throw e}return{command:i,escapedCommand:r,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},ue.exports.command=(e,t)=>{const[s,...n]=T(e);return b(s,n,t)},ue.exports.commandSync=(e,t)=>{const[s,...n]=T(e);return b.sync(s,n,t)},ue.exports.node=(e,t,s={})=>{t&&!Array.isArray(t)&&"object"==typeof t&&(s=t,t=[]);const n=c.node(s),o=process.execArgv.filter(e=>!e.startsWith("--inspect")),{nodePath:i=process.execPath,nodeOptions:r=o}=s;return b(i,[...r,e,...Array.isArray(t)?t:[]],{...s,stdin:void 0,stdout:void 0,stderr:void 0,stdio:n,shell:!1})},ue.exports}(),jt=se(Gt);class Ht{constructor(e={}){this.port=null,this.process=null,this.iflowPath=null,this.exitHandler=null,this.isCleaningUp=!1,this.logger=e.logger||z,this.startPort=e.startPort||8090,this.stream=e.stream||!1}get url(){if(!this.port)throw new E("iFlow process not started");return`ws://localhost:${this.port}/acp`}isRunning(){return!!this.process&&!this.process.killed&&null===this.process.exitCode}isWindows(){return"win32"===r.platform()}which(e){try{const t=this.isWindows()?"where":"which",s=l.execSync(`${t} ${e}`,{encoding:"utf-8",windowsHide:!0});return s.trim().split("\n")[0].trim()||null}catch{return null}}fileExists(t){try{return e.existsSync(t)&&e.statSync(t).isFile()}catch{return!1}}getFallbackLocations(){const e=r.homedir(),t=r.platform();if(this.isWindows())return[s.join(e,"AppData","Roaming","npm","iflow.cmd"),s.join(e,"AppData","Local","npm","iflow.cmd"),s.join(e,"AppData","Roaming","npm","iflow.exe"),s.join("C:","Program Files","nodejs","iflow.cmd"),s.join("C:","Program Files (x86)","nodejs","iflow.cmd"),s.join(e,".npm-global","iflow.cmd"),s.join(e,"node_modules",".bin","iflow.cmd")];{const n=["/usr/local/bin/iflow",s.join(e,".npm-global","bin","iflow"),s.join(e,".local","bin","iflow"),s.join(e,"node_modules",".bin","iflow"),s.join(e,".yarn","bin","iflow"),s.join(e,".config","yarn","global","node_modules",".bin","iflow"),s.join(e,".local","share","pnpm","iflow"),"/usr/bin/iflow"];return"darwin"===t&&"arm64"===r.arch()&&n.unshift("/opt/homebrew/bin/iflow"),n}}findIflowPath(){let e=this.which("iflow");if(e){if(this.isWindows()&&!e.endsWith(".cmd")&&!e.endsWith(".exe")){const t=e+".cmd";this.fileExists(t)&&(e=t)}return this.logger.debug(`Found iflow at: ${e}`),e}const t=this.getFallbackLocations();for(const e of t)if(this.fileExists(e))return this.logger.debug(`Found iflow at: ${e}`),e;const s=null!==this.which("npm"),n=null!==this.which("node");let o;throw o=this.isWindows()?s||n?"iFlow CLI not found. Please install it using one of the following commands:\n\nUsing npm (recommended):\n npm install -g @iflow-ai/iflow-cli@latest\n\nUsing Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\nUsing pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\nAfter installation, please restart your terminal or command prompt.":"iFlow requires Node.js, but it is not installed on your system.\n\nPlease install Node.js first: https://nodejs.org/\n\nAfter installing Node.js, install iFlow with:\n npm install -g @iflow-ai/iflow-cli@latest":'iFlow CLI not found. Please install it using one of the following methods:\n\nš Mac/Linux users (recommended installation script):\n bash -c "$(curl -fsSL https://cloud.iflow.cn/iflow-cli/install.sh)"\n\nOr using npm:\n npm install -g @iflow-ai/iflow-cli@latest\n\nOr using Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\nOr using pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\nš§ Ubuntu/Debian users may need:\n sudo npm install -g @iflow-ai/iflow-cli@latest',new y(o)}isPortAvailable(e,t=1e3){return new Promise(s=>{const n=c.createServer(),o=setTimeout(()=>{n.close(),s(!1)},t);n.listen(e,"localhost",()=>{clearTimeout(o),n.once("close",()=>{s(!0)}),n.close()}),n.once("error",()=>{clearTimeout(o),s(!1)})})}async findAvailablePort(){for(let e=0;e<10;e++){const t=this.startPort+e;if(await this.isPortAvailable(t))return this.logger.debug(`Found available port: ${t}`),t}throw new I(`No available port found in range ${this.startPort}-${this.startPort+10-1}. Please specify a different port range or free up some ports.`)}async start(){if(this.isRunning())return this.url;this.iflowPath=this.findIflowPath(),this.port=await this.findAvailablePort();const e=[this.iflowPath,"--experimental-acp","--port",this.port.toString()];this.stream&&e.push("--stream"),this.logger.info(`Starting iFlow process: ${e.join(" ")}`);try{if(this.process=jt(e[0],e.slice(1),{stdio:["ignore","pipe","pipe"],detached:!1,cleanup:!0,windowsHide:!0,reject:!1}),await this.onSpawn(),!this.isRunning()){let e="iFlow process exited immediately";throw this.process.stderr&&(e+=`: ${this.process.stderr}`),new Error(e)}return this.registerExitHandler(),this.logger.info(`iFlow process started on port ${this.port} (PID: ${this.process.pid})`),this.url}catch(e){throw this.port=null,this.process=null,new E(`Failed to start iFlow process: ${K(e)}`)}}registerExitHandler(){this.exitHandler||(this.exitHandler=()=>{if(!this.isCleaningUp&&this.process&&this.isRunning()){this.isCleaningUp=!0,this.logger.debug("Parent process exiting, cleaning up child process");try{if(this.isWindows())try{l.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:Ht.TASKKILL_TIMEOUT_EXIT_HANDLER,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill failed: ${K(e)}`)}else this.process.kill("SIGKILL")}catch(e){this.logger.debug(`Error during process cleanup: ${K(e)}`)}finally{this.isCleaningUp=!1}}},process.on("exit",this.exitHandler),process.on("SIGINT",this.exitHandler),process.on("SIGTERM",this.exitHandler),this.isWindows()&&process.on("SIGBREAK",this.exitHandler))}unregisterExitHandler(){this.exitHandler&&(process.off("exit",this.exitHandler),process.off("SIGINT",this.exitHandler),process.off("SIGTERM",this.exitHandler),this.isWindows()&&process.off("SIGBREAK",this.exitHandler),this.exitHandler=null)}async stop(){if(this.process){if(this.unregisterExitHandler(),!this.isRunning())return this.port=null,void(this.process=null);this.logger.info(`Stopping iFlow process (PID: ${this.process.pid})`);try{if(this.isWindows())try{l.execSync(`taskkill /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:3e3,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill (graceful shutdown) failed: ${K(e)}`)}else this.process.kill("SIGTERM");if(await Promise.race([this.process.then(()=>{},()=>{}),new Promise(e=>setTimeout(()=>e(),5e3))]),this.isRunning()){if(this.logger.warn("iFlow process did not terminate gracefully, forcing kill"),this.isWindows())try{l.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:Ht.TASKKILL_TIMEOUT_STOP,stdio:"ignore"})}catch(e){this.logger.warn(`taskkill /F /T failed, process may have already exited or is inaccessible: ${K(e)}`)}else this.process.kill("SIGKILL");await this.process.then(()=>{},()=>{})}else this.logger.info("iFlow process terminated gracefully")}catch(e){this.logger.error(`Error stopping iFlow process: ${K(e)}`)}finally{this.port=null,this.process=null}}}async onSpawn(e=5e3){return new Promise((t,s)=>{if(!this.process)return void s(new Error("Process not initialized"));const n=setTimeout(()=>{s(new Error(`Process spawn timeout after ${e}ms`))},e);this.process.once("spawn",()=>{clearTimeout(n),setTimeout(t,2e3)})})}}Ht.TASKKILL_TIMEOUT_EXIT_HANDLER=3e3,Ht.TASKKILL_TIMEOUT_STOP=5e3;class Qt{constructor(e={}){this.protocol=null,this.transport=null,this.connected=!1,this.authenticated=!1,this.messageTask=null,this.messageQueue=[],this.pendingToolCalls=new Map,this.pendingAskUserQuestionsRequestId=null,this.pendingQuestions=[],this.pendingExitPlanModeRequestId=null,this.pendingPermissionRequests=new Map,this.url=null,this.sessionId=null,this.processManager=null,this.processStarted=!1,this.modes=null,this.models=null,this.availableCommands=[],this.availableAgents=[],this.availableSkills=[],this.availableMcpServers=[],this.config={get:async e=>{switch(e){case"models":return this.models?.availableModels||[];case"model":return this.models?.currentModelId||null;case"modes":return this.modes?.availableModes||[];case"mode":return this.modes?.currentModeId||null;case"commands":return this.availableCommands;case"agents":return this.availableAgents;case"skills":return this.availableSkills;case"mcpServers":return this.availableMcpServers;default:throw new Error(`Unknown config key: ${e}`)}},set:async(e,t)=>{if(!this.connected||!this.protocol||!this.sessionId)throw new T("Not connected. Call connect() first.");switch(e){case"model":{const e=t;try{const t=await this.protocol.setModel({sessionId:this.sessionId,modelId:e});if(!t||!this.models){throw new Error(t?"Models not available":"No result returned from server")}this.models.currentModelId=t,this.logger.info(`Set model to: ${t}`)}catch(t){throw this.logger.error(`Failed to set model to ${e}: ${K(t)}`),t}break}case"mode":{const e=t;try{const t=await this.protocol.setMode({sessionId:this.sessionId,modeId:e});if(!t||!this.modes){throw new Error(t?"Modes not available":"No result returned from server")}this.modes.currentModeId=t,this.logger.info(`Set mode to: ${t}`)}catch(t){throw this.logger.error(`Failed to set mode to ${e}: ${K(t)}`),t}break}default:throw new Error(`Cannot set config key: ${e}. Only 'model' and 'mode' are supported.`)}}},this.options={url:"ws://localhost:8090/acp",cwd:process.cwd(),timeout:3e4,logLevel:"INFO",fileMaxSize:10485760,permissionMode:P.AUTO,authMethodId:"iflow",autoStartProcess:!0,processStartPort:8090,...e},this.logger=new B({level:this.options.logLevel})}async connect(){if(this.connected)this.logger.warn("Already connected");else try{if(this.options.autoStartProcess&&(this.options.url?.startsWith("ws://localhost:")||this.options.url?.startsWith("ws://127.0.0.1:"))){const e=new Z({url:this.options.url,logger:this.logger,timeout:2e3});try{await e.connect(),await e.close(),this.url=this.options.url,this.logger.info(`iFlow already running at ${this.options.url}`)}catch{this.logger.info("iFlow not running, starting process..."),this.processManager=new Ht({logger:this.logger,startPort:this.options.processStartPort,stream:this.options.stream});try{const e=await this.processManager.start();this.url=e,this.processStarted=!0,this.logger.info(`Started iFlow process at ${e}`),await new Promise(e=>setTimeout(e,1e3))}catch(e){throw e instanceof y?(this.logger.error("iFlow not installed"),y):(this.logger.error(`Failed to start iFlow process: ${K(e)}`),new T(`Failed to start iFlow process: ${K(e)}`))}}}let e=null;this.options.fileAccess&&(e=new ee({cwd:this.options.cwd,logger:this.logger,readOnly:this.options.fileReadOnly,maxFileSize:this.options.fileMaxSize,allowedDirs:this.options.fileAllowedDirs}),this.logger.info(`File system access enabled with ${this.options.fileReadOnly?"read-only":"read-write"} mode`)),this.transport=new Z({url:this.options.url,logger:this.logger,timeout:this.options.timeout}),this.protocol=new Y({logger:this.logger,transport:this.transport,fileHandler:e,permissionMode:this.options.permissionMode,autoApproveTypes:this.options.autoApproveTypes}),await this.transport.connect();const t=await this.protocol.initialize({mcpServers:this.options.mcpServers,hooks:this.options.hooks,commands:this.options.commands,agents:this.options.agents});let s;this.authenticated=t.isAuthenticated||!1,this.authenticated||(await this.protocol.authenticate({methodId:this.options.authMethodId,methodInfo:this.options.authMethodInfo}),this.authenticated=!0),this.options.sessionId&&(s=await this.protocol.loadSession({sessionId:this.options.sessionId,mcpServers:this.options.mcpServers})),s=await this.protocol.createSession({cwd:this.options.cwd||process.cwd(),mcpServers:this.options.mcpServers,hooks:this.options.hooks,commands:this.options.commands,agents:this.options.agents,settings:this.options.sessionSettings}),this.sessionId=s.sessionId,s.modes&&(this.modes=s.modes),s._meta?.models&&(this.models=s._meta.models),s._meta?.availableCommands&&(this.availableCommands=s._meta.availableCommands),s._meta?.availableAgents&&(this.availableAgents=s._meta.availableAgents),s._meta?.availableSkills&&(this.availableSkills=s._meta.availableSkills),s._meta?.availableMcpServers&&(this.availableMcpServers=s._meta.availableMcpServers),this.connected=!0,this.messageTask=this.handleMessages(),this.logger.info("Connected to iFlow")}catch(e){throw await this.disconnect(),new T(`Failed to connect: ${K(e)}`)}}async loadSession(e){if(!this.connected||!this.protocol)throw new T("Not connected. Call connect() first.");await this.protocol.loadSession({sessionId:e,cwd:this.options.cwd||process.cwd(),mcpServers:this.options.mcpServers}),this.sessionId=e,this.logger.info(`Loaded session: ${e}`)}async disconnect(){this.connected=!1,this.transport&&await this.transport.close(),this.processManager&&this.processStarted&&await this.processManager.stop(),this.url=null,this.protocol=null,this.transport=null,this.messageTask=null,this.authenticated=!1,this.processManager=null,this.processStarted=!1,this.logger.info("Disconnected from iFlow")}async sendMessage(t,n){if(!this.connected||!this.protocol||!this.sessionId)throw new T("Not connected. Call connect() first.");const o=[{type:"text",text:t}];if(n?.length)for(const t of n)if("object"!=typeof t||"image"!==t.type){if("object"==typeof t&&"selection"===t.type){const e={activeFile:{path:t.uri,cursor:{line:t.line?.start||0,character:0},selectedText:t.data}},s=`Here is the user's editor context as a JSON object. This is for your information only.\n\`\`\`json\n${JSON.stringify(e,null,2)}\n\`\`\``;o.push({type:"text",text:s}),this.logger.debug("Added selection context");continue}if("string"==typeof t){const n=s.resolve(this.options.cwd||process.cwd(),t),i=s.parse(t);if(!e.existsSync(n)){this.logger.warn(`File not found, skipping: ${n}`);continue}const r=i.ext.toLowerCase();if([".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg"].includes(r))try{const t=e.readFileSync(n).toString("base64"),s={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".bmp":"image/bmp",".webp":"image/webp",".svg":"image/svg+xml"};o.push({type:"image",data:t,mimeType:s[r]||"image/unknown"}),this.logger.debug(`Added image file: ${i.base}`)}catch(e){this.logger.error(`Failed to read image file ${n}: ${K(e)}`);continue}else if([".mp3",".wav",".m4a",".ogg",".flac"].includes(r))try{const t=e.readFileSync(n).toString("base64"),s={".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".flac":"audio/flac"};o.push({type:"audio",data:t,mimeType:s[r]||"audio/unknown"}),this.logger.debug(`Added audio file: ${i.base}`)}catch(e){this.logger.error(`Failed to read audio file ${n}: ${K(e)}`);continue}else{const t=e.statSync(n);o.push({type:"resource_link",uri:`file://${n}`,name:i.base,title:i.name,size:t.size}),this.logger.debug(`Added resource link: ${i.base}`)}}}else o.push({type:"image",data:t.data,mimeType:t.mimeType}),this.logger.debug("Added image data");await this.protocol.sendPrompt({sessionId:this.sessionId,prompt:o})}async interrupt(){if(!this.connected||!this.protocol||!this.sessionId)throw new T("Not connected");await this.protocol.cancelSession({sessionId:this.sessionId}),this.logger.info("Sent interrupt signal")}async*receiveMessages(){if(!this.connected)throw new T("Not connected");for(;this.connected;)try{this.messageQueue.length>0?yield this.messageQueue.shift():await new Promise(e=>setTimeout(e,100))}catch{continue}}async approveToolCall(e,t=U.ALLOW){if(!this.pendingToolCalls.has(e))throw new Error(`Unknown tool call: ${e}`);this.logger.info(`Approved tool call ${e} with outcome ${t}`),this.pendingToolCalls.delete(e)}async rejectToolCall(e){if(!this.pendingToolCalls.has(e))throw new Error(`Unknown tool call: ${e}`);this.logger.info(`Rejected tool call ${e}`),this.pendingToolCalls.delete(e)}async respondToAskUserQuestions(e){if(!this.connected||!this.protocol)throw new T("Not connected");if(null===this.pendingAskUserQuestionsRequestId)throw new Error("No pending ask_user_questions request");for(const t of this.pendingQuestions){const s=e[t.header];if(void 0===s)throw new v(`Missing answer for question: ${t.header}`);if(t.multiSelect){if(!Array.isArray(s))throw new v(`Question "${t.header}" requires multiple selections (array)`);const e=t.options?.map(e=>e.label)||[];for(const n of s)if(!e.includes(n))throw new v(`Invalid option "${n}" for question "${t.header}"`)}else{if(Array.isArray(s))throw new v(`Question "${t.header}" requires single selection (string)`);if(!t.options.map(e=>e.label).includes(s))throw new v(`Invalid option "${s}" for question "${t.header}"`)}}await this.protocol.respondToAskUserQuestions(this.pendingAskUserQuestionsRequestId,e),this.pendingAskUserQuestionsRequestId=null,this.pendingQuestions=[],this.logger.info("Sent ask_user_questions response")}async respondToExitPlanMode(e){if(!this.connected||!this.protocol)throw new T("Not connected");if(null===this.pendingExitPlanModeRequestId)throw new Error("No pending exit_plan_mode request");await this.protocol.respondToExitPlanMode(this.pendingExitPlanModeRequestId,e),this.pendingExitPlanModeRequestId=null,this.logger.info("Sent exit_plan_mode response: "+(e?"approved":"rejected"))}async respondToToolConfirmation(e,t){if(!this.connected||!this.protocol)throw new T("Not connected");if(!this.pendingPermissionRequests.has(e))throw new Error(`No pending permission request with ID: ${e}`);await this.protocol.sendPermissionResponse(e,t),this.pendingPermissionRequests.delete(e),this.logger.info(`Sent tool confirmation response for request ${e}: ${t}`)}async cancelToolConfirmation(e){if(!this.connected||!this.protocol)throw new T("Not connected");if(!this.pendingPermissionRequests.has(e))throw new Error(`No pending permission request with ID: ${e}`);await this.protocol.cancelPermissionResponse(e),this.pendingPermissionRequests.delete(e),this.logger.info(`Cancelled tool confirmation request: ${e}`)}async setThink(e){if(!this.connected||!this.protocol||!this.sessionId)throw new T("Not connected. Call connect() first.");try{const t=await this.protocol.setThink({sessionId:this.sessionId,thinkEnabled:e.enabled,thinkConfig:e.config});return this.logger.info(`Set think mode: enabled=${t.currentThinkEnabled}, config=${t.currentThinkConfig||"default"}`),t}catch(e){throw this.logger.error(`Failed to set think mode: ${K(e)}`),e}}async handleMessages(){if(this.protocol)try{for await(const e of this.protocol.handleMessages()){const t=this.processProtocolMessage(e);t&&this.messageQueue.push(t)}}catch(e){this.logger.error(`Error in message handler: ${K(e)}`);const t={type:D.ERROR,code:-1,message:String(K(e))};this.messageQueue.push(t)}}processProtocolMessage(e){switch(e.type){case W.SESSION_UPDATE:{const{updateData:t}=e;let s,n;switch("agentId"in t&&t.agentId&&(s=t.agentId,n=function(e){const t=e.split("-");return"subagent"!==t[0]||t.length<4?{agentId:e}:4===t.length?{agentId:e,taskId:["null","undefined"].includes(t[1])?void 0:t[1],agentIndex:parseInt(t[2])||void 0,timestamp:parseInt(t[3])||void 0}:{agentId:e,taskId:t.slice(1,-2).join("-"),agentIndex:parseInt(t[t.length-2])||void 0,timestamp:parseInt(t[t.length-1])||void 0}}(s)),t.sessionUpdate){case Q.PLAN:{const e=t.entries?.map(e=>({content:e.content||"",status:e.status||C.PENDING,priority:e.priority||N.MEDIUM}));return e&&e?.length>0?{type:D.PLAN,entries:e}:null}case Q.TOOL_CALL:{const e={type:D.TOOL_CALL,id:t.toolCallId||"",label:t.title||"Tool",icon:{type:q.EMOJI,value:"š§"},status:t.status||k.IN_PROGRESS,toolName:t.toolName,args:t.args};return s&&(e.agentId=s,e.agentInfo=n),this.pendingToolCalls.set(e.id,e),{...e}}case Q.TOOL_CALL_UPDATE:{const e=t.toolCallId;let o;if(this.pendingToolCalls.has(e)?(o=this.pendingToolCalls.get(e),o.status=t.status||k.COMPLETED,t.toolName&&(o.toolName=t.toolName),!o.agentId&&s&&(o.agentId=s),!o.agentInfo&&n&&(o.agentInfo=n)):(o={type:D.TOOL_CALL,id:e,label:t.title||"Tool",icon:{type:q.EMOJI,value:"š§"},status:t.status||k.COMPLETED,toolName:t.toolName},s&&(o.agentId=s,o.agentInfo=n),this.pendingToolCalls.set(e,o)),t.content&&t.content?.length>0){let e;const s=[];for(const n of t.content)"args"in n&&(e=n.args),"content"===n.type&&"text"===n.content?.type&&s.push(n.content.text||"");void 0!==e&&(o.args=e),s.length>0&&(o.output=s.join("\n"))}return{...o}}case Q.USER_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t)return{type:D.USER,chunks:[{text:t}]}}return null}case Q.AGENT_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:D.ASSISTANT,chunk:{text:t}};return s&&(e.agentId=s,e.agentInfo=n),e}}return null}case Q.AGENT_THOUGHT_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:D.ASSISTANT,chunk:{thought:t}};return s&&(e.agentId=s,e.agentInfo=n),e}}}default:return null}}case W.RESPONSE:{const t=e.result;return t&&"object"==typeof t&&"stopReason"in t?{type:D.TASK_FINISH,stopReason:t.stopReason}:null}case W.ERROR:return{type:D.ERROR,code:e.code||-1,message:e.error||"Unknown error"};case W.ASK_USER_QUESTIONS:{const t=e,{questions:s}=t.params||{};return null!==this.pendingAskUserQuestionsRequestId?(this.logger.warn("Another ask_user_questions request is already pending, ignoring new request"),null):(this.pendingAskUserQuestionsRequestId=t.requestId,this.pendingQuestions=s||[],{type:D.ASK_USER_QUESTIONS,questions:s||[]})}case W.EXIT_PLAN_MODE:{const t=e,{plan:s}=t.params||{};return null!==this.pendingExitPlanModeRequestId?(this.logger.warn("Another exit_plan_mode request is already pending, ignoring new request"),null):(this.pendingExitPlanModeRequestId=t.requestId,{type:D.EXIT_PLAN_MODE,plan:s||""})}case"permission_request":{const t=e,{requestId:s,sessionId:n,toolCall:o,options:i}=t;return this.pendingPermissionRequests.has(s)?(this.logger.warn(`Permission request ${s} is already pending, ignoring new request`),null):(this.pendingPermissionRequests.set(s,{toolCall:o,options:i,sessionId:n}),{type:D.PERMISSION_REQUEST,requestId:s,sessionId:n,toolCall:o,options:i})}default:return null}}}function Wt(e){let t,s=!1,n="text";if(e.startsWith("//"))s=!0,n="control";else try{t=JSON.parse(e),t&&"method"in t?n=`method:${t.method}`:t&&("result"in t||"error"in t)?n="response":t&&"type"in t&&(n=t.type)}catch{}return{isControl:s,messageType:n,rawData:e,jsonData:t,timestamp:Date.now()}}class Kt extends Qt{constructor(e,t=!0){super(e),this.rawQueue=[],this.rawHistory=[],this.rawQueueResolvers=[],this.messageQueueResolvers=[],this.captureRaw=t}async handleMessages(){if(this.protocol)try{if(this.captureRaw&&this.transport){const e=this.captureRawStream(),t=this.handleParsedStream();await Promise.all([e,t])}else await super.handleMessages()}catch(e){this.logger.error(`Error in message handler: ${K(e)}`)}}async captureRawStream(){if(this.transport)try{for await(const e of this.transport.receive()){const t=Wt("string"==typeof e?e:JSON.stringify(e));this.rawQueue.push(t),this.rawHistory.push(t);const s=this.rawQueueResolvers.shift();s&&s(t)}}catch(e){this.logger.error(`Error capturing raw stream: ${K(e)}`)}}async handleParsedStream(){if(this.protocol)for await(const e of this.protocol.handleMessages()){const t=this.processProtocolMessage(e);if(t){const e=this.messageQueueResolvers.shift();e&&e(t)}}}async*receiveRawMessages(){for(;this.connected||this.rawQueue.length>0;)try{if(this.rawQueue.length>0)yield this.rawQueue.shift();else{const e=await Promise.race([new Promise(e=>{this.rawQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),100)})]);yield e}}catch(e){if(e instanceof Error&&"Timeout"===e.message)continue;throw e}}async*receiveDualStream(){const e=[],t=[];for(;this.connected||this.rawQueue.length>0||e.length>0||t.length>0;)try{let e,t;e=this.rawQueue.length>0?this.rawQueue.shift():await Promise.race([new Promise(e=>{this.rawQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),10)})]);try{t=await Promise.race([new Promise(e=>{this.messageQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),10)})])}catch{}e.parsedMessage=t,yield[e,t]}catch(e){if(!(e instanceof Error&&"Timeout"===e.message))throw e;try{const e=await Promise.race([new Promise(e=>{this.messageQueueResolvers.push(e)}),new Promise((e,t)=>{setTimeout(()=>t(new Error("Timeout")),10)})]),t=Wt("<no-raw-data>");t.messageType="parsed_only",yield[t,e]}catch(e){if(e instanceof Error&&"Timeout"===e.message)continue;throw e}}}getRawHistory(){return[...this.rawHistory]}getProtocolStats(){const e={totalMessages:this.rawHistory.length,messageTypes:{},controlMessages:0,jsonMessages:0,textMessages:0,errors:0};for(const t of this.rawHistory)t.messageType&&(e.messageTypes[t.messageType]=(e.messageTypes[t.messageType]||0)+1),t.isControl?e.controlMessages++:t.jsonData?e.jsonMessages++:e.textMessages++,t.jsonData&&"error"in t.jsonData&&e.errors++;return e}async sendRaw(e){if(!this.transport)throw new Error("Not connected");await this.transport.send(e);const t="string"==typeof e?e:JSON.stringify(e).substring(0,100);this.logger.info(`Sent raw data: ${t}`)}}async function Bt(e,t,s){const n=[],o=new Qt(s);await o.connect();try{await o.sendMessage(e,t);for await(const e of o.receiveMessages())if(e.type===D.ASSISTANT&&e.chunk.text)n.push(e.chunk.text);else if(e.type===D.TASK_FINISH)break}finally{await o.disconnect()}return n.join("")}async function*zt(e,t,s){const n=new Qt(s);await n.connect();try{await n.sendMessage(e,t);for await(const e of n.receiveMessages())if(e.type===D.ASSISTANT&&e.chunk.text)yield e.chunk.text;else if(e.type===D.TASK_FINISH)break}finally{await n.disconnect()}}export{$ as ApprovalMode,A as AuthenticationError,T as ConnectionError,O as HookEventType,Qt as IFlowClient,g as IFlowError,y as IFlowNotInstalledError,E as IFlowProcessError,S as JSONDecodeError,R as LogLevel,D as MessageType,_ as PermissionError,P as PermissionMode,N as PlanPriority,C as PlanStatus,I as PortNotAvailableError,b as ProtocolError,Kt as RawDataClient,M as StopReason,w as TimeoutError,U as ToolCallConfirmationOutcome,F as ToolCallConfirmationType,L as ToolCallContentType,q as ToolCallIconType,k as ToolCallStatus,x as TransportError,v as ValidationError,Bt as query,zt as queryStream};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iflow-ai/iflow-cli-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-beta.0",
|
|
4
4
|
"description": "TypeScript SDK for iFlow CLI",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
"dev": "rollup -c && dts-bundle-generator --config dts.config.cjs",
|
|
18
18
|
"build": "NODE_ENV=production rollup -c && dts-bundle-generator --config dts.config.cjs",
|
|
19
19
|
"test": "jest",
|
|
20
|
+
"test:ci": "jest --ci --coverage --maxWorkers=2",
|
|
21
|
+
"test:coverage": "jest --coverage",
|
|
22
|
+
"test:watch": "jest --watch",
|
|
20
23
|
"prepublishOnly": "npm run build",
|
|
21
24
|
"prebuild": "npm run lint && rimraf dist",
|
|
22
25
|
"lint": "tsc --noEmit && eslint src/**/*.ts",
|
|
@@ -28,7 +31,8 @@
|
|
|
28
31
|
"dist",
|
|
29
32
|
"README.md",
|
|
30
33
|
"README_CN.md",
|
|
31
|
-
"LICENSE"
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"CHANGELOG.md"
|
|
32
36
|
],
|
|
33
37
|
"keywords": [
|
|
34
38
|
"iflow",
|