@iflow-ai/iflow-cli-sdk 0.1.9-beta.1 → 0.1.9
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 +49 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -2
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# 更新日志 (Changelog)
|
|
2
|
+
|
|
3
|
+
所有重要的项目变更都将记录在此文件中。
|
|
4
|
+
|
|
5
|
+
格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.0.0/),
|
|
6
|
+
版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## [0.1.9] - 2026-01-26
|
|
11
|
+
|
|
12
|
+
### 优化
|
|
13
|
+
- 改进跨平台兼容性和稳定性(Windows/macOS/Linux)
|
|
14
|
+
- 优化错误提示信息
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## [0.1.8] - 2025-12-31
|
|
19
|
+
|
|
20
|
+
### 优化
|
|
21
|
+
- 改进错误消息处理,支持详细错误信息展示
|
|
22
|
+
- 增强跨平台支持:修复 Windows 环境 `which` 命令兼容性
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## [0.1.7] - 2025-12-24
|
|
27
|
+
|
|
28
|
+
### 新增能力
|
|
29
|
+
- 支持工具调用参数传递(`args` 字段)
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## [0.1.6] - 2025-12-23
|
|
34
|
+
|
|
35
|
+
### Bug 修复
|
|
36
|
+
- 修复 call_tool status 字段状态共享问题,避免重复消息
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## [0.1.4] - 2025-12-23
|
|
41
|
+
|
|
42
|
+
### 新增能力
|
|
43
|
+
- 新增开发构建模式(`dev` 脚本),跳过代码压缩提升构建速度
|
|
44
|
+
|
|
45
|
+
### 优化
|
|
46
|
+
- 改进进程启动机制:事件驱动替代固定延迟,增加超时保护
|
|
47
|
+
|
|
48
|
+
### Bug 修复
|
|
49
|
+
- 修复配置 URL 传递错误
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("fs"),t=require("path"),o=require("ws"),s=require("fs/promises"),n=require("os"),r=require("net"),i=require("child_process"),a=require("assert"),c=require("events"),l=require("buffer"),d=require("stream"),u=require("util");function p(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var s=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:function(){return e[o]}})}}),t.default=e,Object.freeze(t)}var h,f,m,g,w,y,S,x,T,E,I,v,b,C=p(e),A=p(t),P=p(s),O=p(n),_=p(r),R=p(i);class L extends Error{constructor(e,t){super(e),this.name="IFlowError",this.details=t||{}}}class $ extends L{constructor(e,t){super(e,t),this.name="TimeoutError"}}class N extends L{constructor(e,t){super(e,{rawData:t}),this.name="JSONDecodeError",this.rawData=t}}class M extends L{constructor(e,t){super(e,t),this.name="IFlowNotInstalledError"}}class F extends L{constructor(e,t){super(e,t),this.name="IFlowProcessError"}}class k extends L{constructor(e,t){super(e,t),this.name="PortNotAvailableError"}}class G extends L{constructor(e,t){super(e,t),this.name="ConnectionError"}}class D extends L{constructor(e,t){super(e,t),this.name="TransportError"}}class U extends L{constructor(e,t){super(e,t),this.name="PermissionError"}}class j extends L{constructor(e,t){super(e,t),this.name="ValidationError"}}class H extends L{constructor(e,t){super(e,t),this.name="ProtocolError"}}class W extends L{constructor(e,t){super(e,t),this.name="AuthenticationError"}}exports.LogLevel=void 0,(h=exports.LogLevel||(exports.LogLevel={}))[h.DEBUG=0]="DEBUG",h[h.INFO=1]="INFO",h[h.WARN=2]="WARN",h[h.ERROR=3]="ERROR",exports.PermissionMode=void 0,(f=exports.PermissionMode||(exports.PermissionMode={})).AUTO="auto",f.MANUAL="manual",f.SELECTIVE="selective",exports.ApprovalMode=void 0,(m=exports.ApprovalMode||(exports.ApprovalMode={})).DEFAULT="default",m.AUTO_EDIT="autoEdit",m.YOLO="yolo",m.PLAN="plan",exports.HookEventType=void 0,(g=exports.HookEventType||(exports.HookEventType={})).PRE_TOOL_USE="PreToolUse",g.POST_TOOL_USE="PostToolUse",g.STOP="Stop",g.SUBAGENT_STOP="SubagentStop",g.SET_UP_ENVIRONMENT="SetUpEnvironment",exports.PlanPriority=void 0,(w=exports.PlanPriority||(exports.PlanPriority={})).HIGH="high",w.MEDIUM="medium",w.LOW="low",exports.PlanStatus=void 0,(y=exports.PlanStatus||(exports.PlanStatus={})).PENDING="pending",y.IN_PROGRESS="in_progress",y.COMPLETED="completed",exports.StopReason=void 0,(S=exports.StopReason||(exports.StopReason={})).END_TURN="end_turn",S.MAX_TOKENS="max_tokens",S.REFUSAL="refusal",S.CANCELLED="cancelled",exports.ToolCallStatus=void 0,(x=exports.ToolCallStatus||(exports.ToolCallStatus={})).PENDING="pending",x.IN_PROGRESS="in_progress",x.COMPLETED="completed",x.FAILED="failed",exports.ToolCallContentType=void 0,(T=exports.ToolCallContentType||(exports.ToolCallContentType={})).DIFF="diff",T.MARKDOWN="markdown",exports.ToolCallConfirmationType=void 0,(E=exports.ToolCallConfirmationType||(exports.ToolCallConfirmationType={})).EDIT="edit",E.EXECUTE="execute",E.MCP="mcp",E.FETCH="fetch",E.OTHER="other",exports.ToolCallConfirmationOutcome=void 0,(I=exports.ToolCallConfirmationOutcome||(exports.ToolCallConfirmationOutcome={})).ALLOW="allow",I.ALWAYS_ALLOW="alwaysAllow",I.ALWAYS_ALLOW_TOOL="alwaysAllowTool",I.ALWAYS_ALLOW_MCP_SERVER="alwaysAllowMcpServer",I.REJECT="reject",exports.ToolCallIconType=void 0,(v=exports.ToolCallIconType||(exports.ToolCallIconType={})).URL="url",v.EMOJI="emoji",exports.MessageType=void 0,(b=exports.MessageType||(exports.MessageType={})).PLAN="plan",b.USER="user",b.ASSISTANT="assistant",b.TOOL_CALL="tool_call",b.ERROR="error",b.TASK_FINISH="task_finish";const B="2.0";var K,q,z;function Q(e){if(e instanceof Error){const t=e,o=t.details?.data?.details;return o?`${e.message}\n${o}`: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"}(K||(K={})),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"}(q||(q={})),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"}(z||(z={}));class X{constructor(e={}){const t=e.level||"INFO";this.level=exports.LogLevel[t]}debug(e){this.log(exports.LogLevel.DEBUG,e)}info(e){this.log(exports.LogLevel.INFO,e)}warn(e){this.log(exports.LogLevel.WARN,e)}error(e,t){this.log(exports.LogLevel.ERROR,e,t)}log(e,t,o){if(e<this.level)return;const s=`[${(new Date).toLocaleString("sv-SE").replace("T"," ")}] ${exports.LogLevel[e]}: ${t}${o?`\n${o.stack}`:""}`;switch(e){case exports.LogLevel.DEBUG:console.debug(s);break;case exports.LogLevel.INFO:console.info(s);break;case exports.LogLevel.WARN:console.warn(s);break;case exports.LogLevel.ERROR:console.error(s)}}}const V=new X;function J(e){return!!e&&"id"in e&&"result"in e&&null!=e.result}function Y(e){return!!e&&"id"in e&&"error"in e&&null!=e.error}function Z(e){return!!e&&"method"in e&&!("result"in e)&&!("error"in e)}class ee{constructor(e){this.requestId=0,this.initialized=!1,this.authenticated=!1,this.logger=e.logger||V,this.transport=e.transport,this.fileHandler=e.fileHandler,this.permissionMode=e.permissionMode||exports.PermissionMode.AUTO,this.autoApproveTypes=e.autoApproveTypes||["read","fetch","list"]}nextRequestId(){return++this.requestId}checkAuthenticated(){if(!this.initialized)throw new H("Protocol not initialized. Call initialize() first.");if(!this.authenticated)throw new H("Not authenticated. Call authenticate() first.")}async sendResult(e,t){const o={jsonrpc:B,id:e,result:t};await this.transport.send(o)}async sendError(e,t,o){const s={jsonrpc:B,id:e,error:{code:t,message:o}};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,o){const{timeout:s,timeoutMsg:n=`Timeout after ${s} seconds`}=o||{},r=Date.now();for await(const o of this.transport.receive()){if(o.trim().startsWith("//")){this.logger.debug(`Control message: ${o.trim()}`);continue}let i;try{i=JSON.parse(o.trim())}catch(e){this.logger.error(`Failed to parse response: ${Q(e)}`);continue}if(i.id===e){const e=t(i);if(void 0!==e)return e}if(s&&s>0&&Date.now()-r>s)throw new $(n)}}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(),o={jsonrpc:B,id:t,method:K.INITIALIZE,params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}},...e}};await this.transport.send(o),this.logger.info("Sent initialize request");const s=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new H(`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 H("Connection closed during initialization")}async authenticate(e={}){const t=e.methodId||"iflow";if(this.authenticated)return void this.logger.warn("Already authenticated");const o=this.nextRequestId(),s={jsonrpc:B,id:o,method:K.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(o,e=>{if("error"in e)throw new W(`Authentication failed: ${e.error?.message}`,e.error);const o=e.result||{};return o.methodId===t?(this.authenticated=!0,this.logger.info(`Authentication successful with method: ${o.methodId}`),!0):(this.authenticated=!0,this.logger.warn(`Unexpected methodId in response: ${o.methodId} (expected ${t})`),!0)},{timeout:1e4,timeoutMsg:"Authentication timeout after 10 seconds"}))throw new W("Connection closed during authentication")}async createSession(e={}){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_NEW,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(o),this.logger.info(`Sent session/new request with cwd: ${e.cwd}`);const s=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new H(`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 H(`Invalid session/new response: ${JSON.stringify(t)}`)},{timeout:1e4,timeoutMsg:"Session creation timeout after 10 seconds"});if(s)return s;throw new H("Connection closed while waiting for session/new response")}async loadSession(e){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_LOAD,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(o),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 H("session/load is not supported by the current iFlow version. Use session/new to create a new session instead.",t.error);throw new H(`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 H("Connection closed while waiting for session/load response")}async sendPrompt(e){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_PROMPT,params:e};return await this.transport.send(o),this.logger.info(`Sent prompt with ${e.prompt.length} content blocks`),t}async cancelSession(e){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_CANCEL,params:e};await this.transport.send(o),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: ${Q(t)}`),new N("Invalid JSON received",e)}Z(t)?yield await this.handleClientMessage(t):J(t)?yield{type:"response",id:t.id,result:t.result}:Y(t)&&(yield{type:"error",code:t.error.code,error:t.error.message})}}async handleClientMessage(e){const{method:t}=e;switch(t){case q.FS_READ_TEXT_FILE:return await this.handleReadTextFile(e);case q.FS_WRITE_TEXT_FILE:return await this.handleWriteTextFile(e);case q.SESSION_UPDATE:return await this.handleSessionUpdate(e);case q.SESSION_REQUEST_PERMISSION:return await this.handleRequestPermission(e);case q.PUSH_TOOL_CALL:return await this.handlePushToolCall(e);case q.UPDATE_TOOL_CALL:return await this.handleUpdateToolCall(e);case q.NOTIFY_TASK_FINISH:return await this.handleNotifyTaskFinish(e);default:return await this.handleUnknownMessage(e)}}async handleReadTextFile(e){const{id:t,method:o,params:s}=e,{path:n,limit:r,line:i}=s||{};let a;if(this.logger.info(`fs/read_text_file request for: ${n}`),!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:o}}try{a=await this.fileHandler.readFile(n,i,r)}catch(e){const s=Q(e);return this.logger.error(`Error reading file ${n}: ${s}`),void 0!==t&&await this.sendError(t,-32603,s),{type:"error",code:-32603,error:s,method:o}}return void 0!==t&&await this.sendResult(t,{content:a}),{type:"file_read",path:n,content:a}}async handleWriteTextFile(e){const{id:t,method:o,params:s}=e,{path:n,content:r}=s||{};if(this.logger.info(`fs/write_text_file request for: ${n}`),!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:o}}try{await this.fileHandler.writeFile(n,r)}catch(e){const s=Q(e);return this.logger.error(`Error writing file ${n}: ${s}`),void 0!==t&&await this.sendError(t,-32603,s),{type:"error",code:-32603,error:s,method:o}}return void 0!==t&&await this.sendResult(t,{success:!0}),{type:"file_write",path:n,content:r}}async handleSessionUpdate(e){const{params:t}=e,{sessionId:o,update:s}=t;return{type:"session_update",sessionId:o,updateData:s}}async handleRequestPermission(e){const{id:t,params:o}=e,s=o.toolCall||{},n=o.options||[];let r,i;if(r=this.permissionMode===exports.PermissionMode.AUTO||this.permissionMode!==exports.PermissionMode.MANUAL&&this.autoApproveTypes.includes(s.type||""),r){let e;for(const t of n){const o=t.optionId||"";if("proceed_once"===o){e=o;break}"proceed_always"===o&&(e=o)}!e&&n.length>0&&(e=n[0].optionId||"proceed_once"),i={outcome:{outcome:"selected",optionId:e}}}else i={outcome:{outcome:"cancelled"}};return void 0!==t&&await this.sendResult(t,i),this.logger.info(`Permission request for tool '${s.title||"unknown"}' - Response: ${i.outcome.outcome}`),{type:"tool_confirmation",params:o,response:i}}async handlePushToolCall(e){const{id:t,params:o}=e,s=`tool_${this.nextRequestId()}`,n={id:s};return void 0!==t&&await this.sendResult(t,n),{type:"tool_call",id:s,params:o}}async handleUpdateToolCall(e){const{id:t,params:o}=e;return void 0!==t&&await this.sendResult(t,null),{type:"tool_update",params:o}}async handleNotifyTaskFinish(e){const{id:t,params:o}=e;return void 0!==t&&await this.sendResult(t,null),{type:"task_finish",params:o}}async handleUnknownMessage(e){const{id:t,method:o,params:s}=e;return this.logger.warn(`Unknown method: ${o}`),void 0!==t&&await this.sendError(t,-32601,"Method not found"),{type:"unknown",method:o,params:s}}}class te{constructor(e){this.ws=null,this.connected=!1,this.url=e.url,this.logger=e.logger||V,this.timeout=e.timeout||3e5}get isConnected(){return!!this.ws&&this.connected}checkConnected(){if(!this.isConnected)throw new G("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 $(`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,o)=>{clearTimeout(n),this.connected=!1,t(new Error(`${o} (code: ${e})`))})})}catch(e){if(e instanceof $)throw e;throw new G(`Failed to connect to ${this.url}: ${Q(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: ${Q(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,o)=>{this.ws.send(t,s=>{s?o(s):(this.logger.debug(`Sent message: ${t}`),e())})})}catch(e){throw this.connected=!1,new D(`Failed to send message: ${Q(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 G&&e.details.isClosed){this.logger.info("Connection closed");break}throw new D(`Failed to receive message: ${Q(e)}`)}}receiveRawData(){return new Promise((e,t)=>{if(!this.isConnected)return void t(new G("Not connected"));const o=()=>{this.ws&&(this.ws.off("close",s),this.ws.off("error",n),this.ws.off("message",r))},s=()=>{o(),this.connected=!1,t(new G("Connection closed",{isClosed:!0}))},n=e=>{o(),this.connected=!1,t(e)},r=t=>{o(),e(t.toString())};this.ws&&(this.ws.on("close",s),this.ws.on("error",n),this.ws.on("message",r))})}}class oe{constructor(e={}){this.cwd=e.cwd||process.cwd(),this.logger=e.logger||V,this.readOnly=e.readOnly||!1,this.maxFileSize=e.maxFileSize||10485760,e.allowedDirs?this.allowedDirs=new Set(e.allowedDirs.map(e=>A.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=A.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(e,t,o){if(!this.isPathAllowed(e))throw new U(`Access denied: ${e}`);const s=A.resolve(this.cwd,e);try{if(!C.existsSync(s))throw new j(`File not found: ${e}`);try{await P.access(s,C.constants.R_OK)}catch{throw new U(`Permission denied: ${e}`)}const n=await P.stat(s);if(!n.isFile())throw new j(`Not a file: ${e}`);if(n.size>this.maxFileSize)throw new j(`File too large: ${n.size} bytes (max: ${this.maxFileSize})`);const r=await P.readFile(s,"utf-8");if(void 0!==t||void 0!==o){const s=r.split("\n"),n=t?t-1:0,i=o?n+o:s.length,a=Math.max(0,n),c=Math.min(s.length,i);return this.logger.debug(`Read ${c-a} lines from ${e}`),s.slice(a,c).join("\n")}return this.logger.debug(`Read ${r.length} bytes from ${e}`),r}catch(e){if(e instanceof j||e instanceof U)throw e;throw new j(`Failed to read file: ${Q(e)}`)}}async writeFile(e,t){if(this.readOnly)throw new U("File system is in read-only mode");if(!this.isPathAllowed(e))throw new U(`Access denied: ${e}`);const o=A.resolve(this.cwd,e);try{await P.mkdir(A.dirname(o),{recursive:!0}),await P.writeFile(o,t,"utf-8"),this.logger.debug(`Wrote ${t.length} bytes to ${e}`)}catch(e){throw new j(`Failed to write file: ${Q(e)}`)}}async addAllowedDir(e){const t=A.resolve(this.cwd,e);try{if(!C.existsSync(t))throw new j(`Directory does not exist: ${t}`);if(!(await P.stat(t)).isDirectory())throw new j(`Not a directory: ${t}`);this.allowedDirs.add(t),this.logger.info(`Added allowed directory: ${t}`)}catch(e){if(e instanceof j)throw e;throw new j(`Failed to add ${t} as allowed directory: ${Q(e)}`)}}removeAllowedDir(e){const t=A.resolve(this.cwd,e);this.allowedDirs.delete(t),this.logger.info(`Removed allowed directory: ${t}`)}}var se="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ne(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var re,ie,ae,ce,le,de,ue,pe,he={exports:{}},fe={exports:{}};function me(){if(ie)return re;ie=1,re=s,s.sync=function(e,s){return o(t.statSync(e),e,s)};var t=e;function o(e,t,o){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var o=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!o)return!0;if(-1!==(o=o.split(";")).indexOf(""))return!0;for(var s=0;s<o.length;s++){var n=o[s].toLowerCase();if(n&&e.substr(-n.length).toLowerCase()===n)return!0}return!1}(t,o)}function s(e,s,n){t.stat(e,function(t,r){n(t,!t&&o(r,e,s))})}return re}function ge(){if(ce)return ae;ce=1,ae=o,o.sync=function(e,o){return s(t.statSync(e),o)};var t=e;function o(e,o,n){t.stat(e,function(e,t){n(e,!e&&s(t,o))})}function s(e,t){return e.isFile()&&function(e,t){var o=e.mode,s=e.uid,n=e.gid,r=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=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 o&l||o&c&&n===i||o&a&&s===r||o&d&&0===r}(e,t)}return ae}function we(){if(pe)return ue;pe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,o=t,s=e?";":":",n=function(){if(de)return le;var e;function t(o,s,n){if("function"==typeof s&&(n=s,s={}),!n){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,n){t(o,s||{},function(t,o){t?n(t):e(o)})})}e(o,s||{},function(e,t){e&&("EACCES"===e.code||s&&s.ignoreErrors)&&(e=null,t=!1),n(e,t)})}return de=1,e="win32"===process.platform||se.TESTING_WINDOWS?me():ge(),le=t,t.sync=function(t,o){try{return e.sync(t,o||{})}catch(e){if(o&&o.ignoreErrors||"EACCES"===e.code)return!1;throw e}},le}(),r=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,o)=>{const n=o.colon||s,r=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(o.path||process.env.PATH||"").split(n)],i=e?o.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(n):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:r,pathExt:a,pathExtExe:i}},a=(e,t,s)=>{"function"==typeof t&&(s=t,t={}),t||(t={});const{pathEnv:a,pathExt:c,pathExtExe:l}=i(e,t),d=[],u=s=>new Promise((n,i)=>{if(s===a.length)return t.all&&d.length?n(d):i(r(e));const c=a[s],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=o.join(l,e),h=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;n(p(h,s,0))}),p=(e,o,s)=>new Promise((r,i)=>{if(s===c.length)return r(u(o+1));const a=c[s];n(e+a,{pathExt:l},(n,i)=>{if(!n&&i){if(!t.all)return r(e+a);d.push(e+a)}return r(p(e,o,s+1))})});return s?u(0).then(e=>s(null,e),s):u(0)};return ue=a,a.sync=(e,t)=>{t=t||{};const{pathEnv:s,pathExt:a,pathExtExe:c}=i(e,t),l=[];for(let r=0;r<s.length;r++){const i=s[r],d=/^".*"$/.test(i)?i.slice(1,-1):i,u=o.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<a.length;e++){const o=p+a[e];try{if(n.sync(o,{pathExt:c})){if(!t.all)return o;l.push(o)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw r(e)},ue}var ye,Se,xe,Te={exports:{}};function Ee(){if(ye)return Te.exports;ye=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 Te.exports=e,Te.exports.default=e,Te.exports}var Ie,ve,be,Ce,Ae,Pe,Oe,_e,Re,Le,$e,Ne,Me,Fe,ke={};function Ge(){return be?ve:(be=1,ve=/^#!(.*)/)}function De(){if(Ae)return Ce;Ae=1;const e=Ge();return Ce=(t="")=>{const o=t.match(e);if(!o)return null;const[s,n]=o[0].replace(/#! ?/,"").split(" "),r=s.split("/").pop();return"env"===r?n:n?`${r} ${n}`:r},Ce}function Ue(){if(Re)return _e;Re=1;const o=t,s=function(){if(xe)return Se;xe=1;const e=t,o=we(),s=Ee();function n(t,n){const r=t.options.env||process.env,i=process.cwd(),a=null!=t.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(t.options.cwd)}catch(e){}let l;try{l=o.sync(t.command,{path:r[s({env:r})],pathExt:n?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?t.options.cwd:"",l)),l}return Se=function(e){return n(e)||n(e,!0)}}(),n=function(){if(Ie)return ke;Ie=1;const e=/([()\][%!^"`<>&|;, *?])/g;return ke.command=function(t){return t.replace(e,"^$1")},ke.argument=function(t,o){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),o&&(t=t.replace(e,"^$1")),t},ke}(),r=function(){if(Oe)return Pe;Oe=1;const t=e,o=De();return Pe=function(e){const s=Buffer.alloc(150);let n;try{n=t.openSync(e,"r"),t.readSync(n,s,0,150,0),t.closeSync(n)}catch(e){}return o(s.toString())},Pe}(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){if(!i)return e;const t=function(e){e.file=s(e);const t=e.file&&r(e.file);return t?(e.args.unshift(e.file),e.command=t,s(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const s=c.test(t);e.command=o.normalize(e.command),e.command=n.command(e.command),e.args=e.args.map(e=>n.argument(e,s));const r=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${r}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}return _e=function(e,t,o){t&&!Array.isArray(t)&&(o=t,t=null);const s={command:e,args:t=t?t.slice(0):[],options:o=Object.assign({},o),file:void 0,original:{command:e,args:t}};return o.shell?s:l(s)},_e}function je(){if($e)return Le;$e=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 o(o,s){return e&&1===o&&!s.file?t(s.original,"spawn"):null}return Le={hookChildProcess:function(t,s){if(!e)return;const n=t.emit;t.emit=function(e,r){if("exit"===e){const e=o(r,s);if(e)return n.call(t,"error",e)}return n.apply(t,arguments)}},verifyENOENT:o,verifyENOENTSync:function(o,s){return e&&1===o&&!s.file?t(s.original,"spawnSync"):null},notFoundError:t},Le}function He(){if(Ne)return fe.exports;Ne=1;const e=i,t=Ue(),o=je();function s(s,n,r){const i=t(s,n,r),a=e.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}return fe.exports=s,fe.exports.spawn=s,fe.exports.sync=function(s,n,r){const i=t(s,n,r),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},fe.exports._parse=t,fe.exports._enoent=o,fe.exports}function We(){return Fe?Me:(Fe=1,Me=e=>{const t="string"==typeof e?"\n":"\n".charCodeAt(),o="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,e.length-1)),e[e.length-1]===o&&(e=e.slice(0,e.length-1)),e})}var Be,Ke={exports:{}};function qe(){return Be||(Be=1,function(e){const o=t,s=Ee(),n=e=>{let t;e={cwd:process.cwd(),path:process.env[s()],execPath:process.execPath,...e};let n=o.resolve(e.cwd);const r=[];for(;t!==n;)r.push(o.join(n,"node_modules/.bin")),t=n,n=o.resolve(n,"..");const i=o.resolve(e.cwd,e.execPath,"..");return r.push(i),r.concat(e.path).join(o.delimiter)};e.exports=n,e.exports.default=n,e.exports.env=t=>{const o={...(t={env:process.env,...t}).env},n=s({env:o});return t.path=o[n],o[n]=e.exports(t),o}}(Ke)),Ke.exports}var ze,Qe,Xe={exports:{}},Ve={exports:{}};function Je(){if(ze)return Ve.exports;ze=1;const e=(e,t)=>{for(const o of Reflect.ownKeys(t))Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(t,o));return e};return Ve.exports=e,Ve.exports.default=e,Ve.exports}function Ye(){if(Qe)return Xe.exports;Qe=1;const e=Je(),t=new WeakMap,o=(o,s={})=>{if("function"!=typeof o)throw new TypeError("Expected a function");let n,r=0;const i=o.displayName||o.name||"<anonymous>",a=function(...e){if(t.set(a,++r),1===r)n=o.apply(this,e),o=null;else if(!0===s.throw)throw new Error(`Function \`${i}\` can only be called once`);return n};return e(a,o),t.set(a,r),a};return Xe.exports=o,Xe.exports.default=o,Xe.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)},Xe.exports}var Ze,et={},tt={},ot={};var st,nt,rt,it,at,ct={};function lt(){if(st)return ct;st=1,Object.defineProperty(ct,"__esModule",{value:!0}),ct.SIGRTMAX=ct.getRealtimeSignals=void 0;ct.getRealtimeSignals=function(){const s=o-t+1;return Array.from({length:s},e)};const e=function(e,o){return{name:`SIGRT${o+1}`,number:t+o,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},t=34,o=64;return ct.SIGRTMAX=o,ct}function dt(){if(nt)return tt;nt=1,Object.defineProperty(tt,"__esModule",{value:!0}),tt.getSignals=void 0;var e=n,t=(Ze||(Ze=1,Object.defineProperty(ot,"__esModule",{value:!0}),ot.SIGNALS=void 0,ot.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"}]),ot),o=lt();tt.getSignals=function(){const e=(0,o.getRealtimeSignals)();return[...t.SIGNALS,...e].map(s)};const s=function({name:t,number:o,description:s,action:n,forced:r=!1,standard:i}){const{signals:{[t]:a}}=e.constants,c=void 0!==a;return{name:t,number:c?a:o,description:s,supported:c,action:n,forced:r,standard:i}};return tt}function ut(){if(at)return it;at=1;const{signalsByName:e}=function(){if(rt)return et;rt=1,Object.defineProperty(et,"__esModule",{value:!0}),et.signalsByNumber=et.signalsByName=void 0;var e=n,t=dt(),o=lt();const s=function(e,{name:t,number:o,description:s,supported:n,action:r,forced:i,standard:a}){return{...e,[t]:{name:t,number:o,description:s,supported:n,action:r,forced:i,standard:a}}},r=(0,t.getSignals)().reduce(s,{});et.signalsByName=r;const i=function(e,t){const o=a(e,t);if(void 0===o)return{};const{name:s,description:n,supported:r,action:i,forced:c,standard:l}=o;return{[e]:{name:s,number:e,description:n,supported:r,action:i,forced:c,standard:l}}},a=function(t,o){const s=o.find(({name:o})=>e.constants.signals[o]===t);return void 0!==s?s:o.find(e=>e.number===t)},c=function(){const e=(0,t.getSignals)(),s=o.SIGRTMAX+1,n=Array.from({length:s},(t,o)=>i(o,e));return Object.assign({},...n)}();return et.signalsByNumber=c,et}();return it=({stdout:t,stderr:o,all:s,error:n,signal:r,exitCode:i,command:a,escapedCommand:c,timedOut:l,isCanceled:d,killed:u,parsed:{options:{timeout:p}}})=>{i=null===i?void 0:i;const h=void 0===(r=null===r?void 0:r)?void 0:e[r].description,f=(({timedOut:e,timeout:t,errorCode:o,signal:s,signalDescription:n,exitCode:r,isCanceled:i})=>e?`timed out after ${t} milliseconds`:i?"was canceled":void 0!==o?`failed with ${o}`:void 0!==s?`was killed with ${s} (${n})`:void 0!==r?`failed with exit code ${r}`:"failed")({timedOut:l,timeout:p,errorCode:n&&n.code,signal:r,signalDescription:h,exitCode:i,isCanceled:d}),m=`Command ${f}: ${a}`,g="[object Error]"===Object.prototype.toString.call(n),w=g?`${m}\n${n.message}`:m,y=[w,o,t].filter(Boolean).join("\n");return g?(n.originalMessage=n.message,n.message=y):n=new Error(y),n.shortMessage=w,n.command=a,n.escapedCommand=c,n.exitCode=i,n.signal=r,n.signalDescription=h,n.stdout=t,n.stderr=o,void 0!==s&&(n.all=s),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(l),n.isCanceled=d,n.killed=u&&!l,n},it}var pt,ht={exports:{}};function ft(){if(pt)return ht.exports;pt=1;const e=["stdin","stdout","stderr"],t=t=>{if(!t)return;const{stdio:o}=t;if(void 0===o)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 o)return o;if(!Array.isArray(o))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof o}\``);const s=Math.max(o.length,e.length);return Array.from({length:s},(e,t)=>o[t])};return ht.exports=t,ht.exports.node=e=>{const o=t(e);return"ipc"===o?"ipc":void 0===o||"string"==typeof o?[o,o,o,"ipc"]:o.includes("ipc")?o:[...o,"ipc"]},ht.exports}var mt,gt,wt,yt,St,xt,Tt={exports:{}},Et={exports:{}};function It(){return mt||(mt=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 vt(){if(yt)return wt;yt=1;const e=n,t=function(){if(gt)return Tt.exports;gt=1;var e=se.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 o,s=a,n=It(),r=/^win/i.test(e.platform),i=c;"function"!=typeof i&&(i=i.EventEmitter),e.__signal_exit_emitter__?o=e.__signal_exit_emitter__:((o=e.__signal_exit_emitter__=new i).count=0,o.emitted={}),o.infinite||(o.setMaxListeners(1/0),o.infinite=!0),Tt.exports=function(e,n){if(!t(se.process))return function(){};s.equal(typeof e,"function","a callback must be provided for exit handler"),!1===p&&h();var r="exit";return n&&n.alwaysLast&&(r="afterexit"),o.on(r,e),function(){o.removeListener(r,e),0===o.listeners("exit").length&&0===o.listeners("afterexit").length&&l()}};var l=function(){p&&t(se.process)&&(p=!1,n.forEach(function(t){try{e.removeListener(t,u[t])}catch(e){}}),e.emit=g,e.reallyExit=f,o.count-=1)};Tt.exports.unload=l;var d=function(e,t,s){o.emitted[e]||(o.emitted[e]=!0,o.emit(e,t,s))},u={};n.forEach(function(s){u[s]=function(){t(se.process)&&e.listeners(s).length===o.count&&(l(),d("exit",null,s),d("afterexit",null,s),r&&"SIGHUP"===s&&(s="SIGINT"),e.kill(e.pid,s))}}),Tt.exports.signals=function(){return n};var p=!1,h=function(){!p&&t(se.process)&&(p=!0,o.count+=1,n=n.filter(function(t){try{return e.on(t,u[t]),!0}catch(e){return!1}}),e.emit=w,e.reallyExit=m)};Tt.exports.load=h;var f=e.reallyExit,m=function(o){t(se.process)&&(e.exitCode=o||0,d("exit",e.exitCode,null),d("afterexit",e.exitCode,null),f.call(e,e.exitCode))},g=e.emit,w=function(o,s){if("exit"===o&&t(se.process)){void 0!==s&&(e.exitCode=s);var n=g.apply(this,arguments);return d("exit",e.exitCode,null),d("afterexit",e.exitCode,null),n}return g.apply(this,arguments)}}else Tt.exports=function(){return function(){}};return Tt.exports}(),o=(e,t,o,n)=>{if(!s(t,o,n))return;const r=i(o),a=setTimeout(()=>{e("SIGKILL")},r);a.unref&&a.unref()},s=(e,{forceKillAfterTimeout:t},o)=>r(e)&&!1!==t&&o,r=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 wt={spawnedKill:(e,t="SIGTERM",s={})=>{const n=e(t);return o(e,t,s,n),n},spawnedCancel:(e,t)=>{e.kill()&&(t.isCanceled=!0)},setupTimeout:(e,{timeout:t,killSignal:o="SIGTERM"},s)=>{if(0===t||void 0===t)return s;let n;const r=new Promise((s,r)=>{n=setTimeout(()=>{((e,t,o)=>{e.kill(t),o(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))})(e,o,r)},t)}),i=s.finally(()=>{clearTimeout(n)});return Promise.race([r,i])},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:o,detached:s},n)=>{if(!o||s)return n;const r=t(()=>{e.kill()});return n.finally(()=>{r()})}}}var bt,Ct,At,Pt,Ot,_t,Rt,Lt,$t,Nt,Mt,Ft,kt={exports:{}};function Gt(){if(Ct)return bt;Ct=1;const{PassThrough:e}=d;return bt=t=>{t={...t};const{array:o}=t;let{encoding:s}=t;const n="buffer"===s;let r=!1;o?r=!(s||n):s=s||"utf8",n&&(s=null);const i=new e({objectMode:r});s&&i.setEncoding(s);let a=0;const c=[];return i.on("data",e=>{c.push(e),r?a=c.length:a+=e.length}),i.getBufferedValue=()=>o?c:n?Buffer.concat(c,a):c.join(""),i.getBufferedLength=()=>a,i},bt}function Dt(){if(At)return kt.exports;At=1;const{constants:e}=l,t=d,{promisify:o}=u,s=Gt(),n=o(t.pipeline);class r extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function i(t,o){if(!t)throw new Error("Expected a stream");o={maxBuffer:1/0,...o};const{maxBuffer:i}=o,a=s(o);return await new Promise((o,s)=>{const c=t=>{t&&a.getBufferedLength()<=e.MAX_LENGTH&&(t.bufferedData=a.getBufferedValue()),s(t)};(async()=>{try{await n(t,a),o()}catch(e){c(e)}})(),a.on("data",()=>{a.getBufferedLength()>i&&c(new r)})}),a.getBufferedValue()}return kt.exports=i,kt.exports.buffer=(e,t)=>i(e,{...t,encoding:"buffer"}),kt.exports.array=(e,t)=>i(e,{...t,array:!0}),kt.exports.MaxBufferError=r,kt.exports}function Ut(){if(Ot)return Pt;Ot=1;const{PassThrough:e}=d;return Pt=function(){var t=[],o=new e({objectMode:!0});return o.setMaxListeners(0),o.add=s,o.isEmpty=function(){return 0==t.length},o.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(s),o;function s(e){return Array.isArray(e)?(e.forEach(s),this):(t.push(e),e.once("end",n.bind(null,e)),e.once("error",o.emit.bind(o,"error")),e.pipe(o,{end:!1}),this)}function n(e){!(t=t.filter(function(t){return t!==e})).length&&o.readable&&o.end()}},Pt}function jt(){if(Rt)return _t;Rt=1;const e=function(){if(xt)return St;xt=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,St=e}(),t=Dt(),o=Ut(),s=async(e,t)=>{if(e){e.destroy();try{return await t}catch(e){return e.bufferedData}}},n=(e,{encoding:o,buffer:s,maxBuffer:n})=>{if(e&&s)return o?t(e,{encoding:o,maxBuffer:n}):t.buffer(e,{maxBuffer:n})};return _t={handleInput:(t,o)=>{void 0!==o&&void 0!==t.stdin&&(e(o)?o.pipe(t.stdin):t.stdin.end(o))},makeAllStream:(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const s=o();return e.stdout&&s.add(e.stdout),e.stderr&&s.add(e.stderr),s},getSpawnedResult:async({stdout:e,stderr:t,all:o},{encoding:r,buffer:i,maxBuffer:a},c)=>{const l=n(e,{encoding:r,buffer:i,maxBuffer:a}),d=n(t,{encoding:r,buffer:i,maxBuffer:a}),u=n(o,{encoding:r,buffer:i,maxBuffer:2*a});try{return await Promise.all([c,l,d,u])}catch(n){return Promise.all([{error:n,signal:n.signal,timedOut:n.timedOut},s(e,l),s(t,d),s(o,u)])}},validateInputSync:({input:t})=>{if(e(t))throw new TypeError("The `input` option cannot be a stream in sync mode")}},_t}function Ht(){if(Mt)return Nt;Mt=1;const e=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],t=/^[\w.-]+$/,o=/"/g,s=/ +/g;return Nt={joinCommand:(t,o)=>e(t,o).join(" "),getEscapedCommand:(s,n)=>e(s,n).map(e=>(e=>"string"!=typeof e||t.test(e)?e:`"${e.replace(o,'\\"')}"`)(e)).join(" "),parseCommand:e=>{const t=[];for(const o of e.trim().split(s)){const e=t[t.length-1];e&&e.endsWith("\\")?t[t.length-1]=`${e.slice(0,-1)} ${o}`:t.push(o)}return t}}}var Wt,Bt=function(){if(Ft)return he.exports;Ft=1;const e=t,o=i,s=He(),n=We(),r=qe(),a=Ye(),c=ut(),l=ft(),{spawnedKill:d,spawnedCancel:u,setupTimeout:p,validateTimeout:h,setExitHandler:f}=vt(),{handleInput:m,getSpawnedResult:g,makeAllStream:w,validateInputSync:y}=jt(),{mergePromise:S,getSpawnedPromise:x}=function(){if($t)return Lt;$t=1;const e=(async()=>{})().constructor.prototype,t=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(e,t)]);return Lt={mergePromise:(e,o)=>{for(const[s,n]of t){const t="function"==typeof o?(...e)=>Reflect.apply(n.value,o(),e):n.value.bind(o);Reflect.defineProperty(e,s,{...n,value:t})}return e},getSpawnedPromise:e=>new Promise((t,o)=>{e.on("exit",(e,o)=>{t({exitCode:e,signal:o})}),e.on("error",e=>{o(e)}),e.stdin&&e.stdin.on("error",e=>{o(e)})})},Lt}(),{joinCommand:T,parseCommand:E,getEscapedCommand:I}=Ht(),v=(t,o,n={})=>{const i=s._parse(t,o,n);return t=i.command,o=i.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=i.options).cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...n}).env=(({env:e,extendEnv:t,preferLocal:o,localDir:s,execPath:n})=>{const i=t?{...process.env,...e}:e;return o?r.env({env:i,cwd:s,execPath:n}):i})(n),n.stdio=l(n),"win32"===process.platform&&"cmd"===e.basename(t,".exe")&&o.unshift("/q"),{file:t,args:o,options:n,parsed:i}},b=(e,t,o)=>"string"==typeof t||Buffer.isBuffer(t)?e.stripFinalNewline?n(t):t:void 0===o?void 0:"",C=(e,t,s)=>{const n=v(e,t,s),r=T(e,t),i=I(e,t);let l;h(n.options);try{l=o.spawn(n.file,n.args,n.options)}catch(e){const t=new o.ChildProcess,s=Promise.reject(c({error:e,stdout:"",stderr:"",all:"",command:r,escapedCommand:i,parsed:n,timedOut:!1,isCanceled:!1,killed:!1}));return S(t,s)}const y=x(l),E=p(l,n.options,y),C=f(l,n.options,E),A={isCanceled:!1};l.kill=d.bind(null,l.kill.bind(l)),l.cancel=u.bind(null,l,A);const P=a(async()=>{const[{error:e,exitCode:t,signal:o,timedOut:s},a,d,u]=await g(l,n.options,C),p=b(n.options,a),h=b(n.options,d),f=b(n.options,u);if(e||0!==t||null!==o){const a=c({error:e,exitCode:t,signal:o,stdout:p,stderr:h,all:f,command:r,escapedCommand:i,parsed:n,timedOut:s,isCanceled:A.isCanceled,killed:l.killed});if(!n.options.reject)return a;throw a}return{command:r,escapedCommand:i,exitCode:0,stdout:p,stderr:h,all:f,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return m(l,n.options.input),l.all=w(l,n.options),S(l,P)};return he.exports=C,he.exports.sync=(e,t,s)=>{const n=v(e,t,s),r=T(e,t),i=I(e,t);let a;y(n.options);try{a=o.spawnSync(n.file,n.args,n.options)}catch(e){throw c({error:e,stdout:"",stderr:"",all:"",command:r,escapedCommand:i,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=b(n.options,a.stdout,a.error),d=b(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=c({stdout:l,stderr:d,error:a.error,signal:a.signal,exitCode:a.status,command:r,escapedCommand:i,parsed:n,timedOut:a.error&&"ETIMEDOUT"===a.error.code,isCanceled:!1,killed:null!==a.signal});if(!n.options.reject)return e;throw e}return{command:r,escapedCommand:i,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},he.exports.command=(e,t)=>{const[o,...s]=E(e);return C(o,s,t)},he.exports.commandSync=(e,t)=>{const[o,...s]=E(e);return C.sync(o,s,t)},he.exports.node=(e,t,o={})=>{t&&!Array.isArray(t)&&"object"==typeof t&&(o=t,t=[]);const s=l.node(o),n=process.execArgv.filter(e=>!e.startsWith("--inspect")),{nodePath:r=process.execPath,nodeOptions:i=n}=o;return C(r,[...i,e,...Array.isArray(t)?t:[]],{...o,stdin:void 0,stdout:void 0,stderr:void 0,stdio:s,shell:!1})},he.exports}(),Kt=ne(Bt);class qt{constructor(e={}){this.port=null,this.process=null,this.iflowPath=null,this.exitHandler=null,this.isCleaningUp=!1,this.logger=e.logger||V,this.startPort=e.startPort||8090}get url(){if(!this.port)throw new F("iFlow process not started");return`ws://localhost:${this.port}/acp`}isRunning(){return!!this.process&&!this.process.killed&&null===this.process.exitCode}isWindows(){return"win32"===O.platform()}which(e){try{const t=this.isWindows()?"where":"which",o=R.execSync(`${t} ${e}`,{encoding:"utf-8",windowsHide:!0});return o.trim().split("\n")[0].trim()||null}catch{return null}}fileExists(e){try{return C.existsSync(e)&&C.statSync(e).isFile()}catch{return!1}}getFallbackLocations(){const e=O.homedir(),t=O.platform();if(this.isWindows())return[A.join(e,"AppData","Roaming","npm","iflow.cmd"),A.join(e,"AppData","Local","npm","iflow.cmd"),A.join(e,"AppData","Roaming","npm","iflow.exe"),A.join("C:","Program Files","nodejs","iflow.cmd"),A.join("C:","Program Files (x86)","nodejs","iflow.cmd"),A.join(e,".npm-global","iflow.cmd"),A.join(e,"node_modules",".bin","iflow.cmd")];{const o=["/usr/local/bin/iflow",A.join(e,".npm-global","bin","iflow"),A.join(e,".local","bin","iflow"),A.join(e,"node_modules",".bin","iflow"),A.join(e,".yarn","bin","iflow"),A.join(e,".config","yarn","global","node_modules",".bin","iflow"),A.join(e,".local","share","pnpm","iflow"),"/usr/bin/iflow"];return"darwin"===t&&"arm64"===O.arch()&&o.unshift("/opt/homebrew/bin/iflow"),o}}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 o=null!==this.which("npm"),s=null!==this.which("node");let n;throw n=this.isWindows()?o||s?"未找到 iFlow CLI。请使用以下命令安装:\n\n使用 npm (推荐):\n npm install -g @iflow-ai/iflow-cli@latest\n\n使用 Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\n使用 pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\n安装后,请重启终端或命令提示符。":"iFlow 需要 Node.js,但系统中未安装。\n\n请先安装 Node.js: https://nodejs.org/\n\n安装 Node.js 后,使用以下命令安装 iFlow:\n npm install -g @iflow-ai/iflow-cli@latest":'未找到 iFlow CLI。请使用以下命令安装:\n\n🍎 Mac/Linux 用户 (推荐使用安装脚本):\n bash -c "$(curl -fsSL https://cloud.iflow.cn/iflow-cli/install.sh)"\n\n或使用 npm:\n npm install -g @iflow-ai/iflow-cli@latest\n\n或使用 Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\n或使用 pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\n🐧 Ubuntu/Debian 用户可能需要:\n sudo npm install -g @iflow-ai/iflow-cli@latest',new M(n)}isPortAvailable(e,t=1e3){return new Promise(o=>{const s=_.createServer(),n=setTimeout(()=>{s.close(),o(!1)},t);s.listen(e,"localhost",()=>{clearTimeout(n),s.once("close",()=>{o(!0)}),s.close()}),s.once("error",()=>{clearTimeout(n),o(!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 k(`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=Kt(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 F(`Failed to start iFlow process: ${Q(e)}`)}}registerExitHandler(){this.exitHandler||(this.exitHandler=()=>{if(!this.isCleaningUp&&this.process&&this.isRunning()){this.isCleaningUp=!0,this.logger.debug("父进程退出中,清理子进程");try{if(this.isWindows())try{R.execSync(`taskkill /F /T /PID ${this.process.pid}`,{encoding:"utf-8",windowsHide:!0,timeout:qt.TASKKILL_TIMEOUT_EXIT_HANDLER})}catch(e){this.logger.debug(`taskkill 失败: ${Q(e)}`)}else this.process.kill("SIGKILL")}catch(e){this.logger.debug(`清理进程时出错: ${Q(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{R.execSync(`taskkill /T /PID ${this.process.pid}`,{encoding:"utf-8",windowsHide:!0,timeout:3e3})}catch(e){this.logger.debug(`taskkill (优雅关闭) 失败: ${Q(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{R.execSync(`taskkill /F /T /PID ${this.process.pid}`,{encoding:"utf-8",windowsHide:!0,timeout:qt.TASKKILL_TIMEOUT_STOP})}catch(e){this.logger.warn(`taskkill /F /T 失败,进程可能已退出或无法访问: ${Q(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: ${Q(e)}`)}finally{this.port=null,this.process=null}}}async onSpawn(e=5e3){return new Promise((t,o)=>{if(!this.process)return void o(new Error("Process not initialized"));const s=setTimeout(()=>{o(new Error(`Process spawn timeout after ${e}ms`))},e);this.process.once("spawn",()=>{clearTimeout(s),setTimeout(t,2e3)})})}}qt.TASKKILL_TIMEOUT_EXIT_HANDLER=3e3,qt.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"}(Wt||(Wt={}));class zt{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:exports.PermissionMode.AUTO,autoApproveTypes:["read","fetch","list"],authMethodId:"iflow",autoStartProcess:!0,processStartPort:8090,...e},this.logger=new X({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 te({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 qt({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 M?(this.logger.error("iFlow not installed"),M):(this.logger.error(`Failed to start iFlow process: ${Q(e)}`),new G(`Failed to start iFlow process: ${Q(e)}`))}}}let e=null;this.options.fileAccess&&(e=new oe({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 te({url:this.options.url,logger:this.logger,timeout:this.options.timeout}),this.protocol=new ee({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 G(`Failed to connect: ${Q(e)}`)}}async loadSession(e){if(!this.connected||!this.protocol)throw new G("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(e,t){if(!this.connected||!this.protocol||!this.sessionId)throw new G("Not connected. Call connect() first.");const o=[{type:"text",text:e}];if(t?.length)for(const e of t){const t=A.resolve(this.options.cwd||process.cwd(),e),s=A.parse(e);if(!C.existsSync(t)){this.logger.warn(`File not found, skipping: ${t}`);continue}const n=s.ext.toLowerCase();if([".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg"].includes(n))try{const e=C.readFileSync(t).toString("base64"),r={".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:e,mimeType:r[n]||"image/unknown"}),this.logger.debug(`Added image file: ${s.base}`)}catch(e){this.logger.error(`Failed to read image file ${t}: ${Q(e)}`);continue}else if([".mp3",".wav",".m4a",".ogg",".flac"].includes(n))try{const e=C.readFileSync(t).toString("base64"),r={".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".flac":"audio/flac"};o.push({type:"audio",data:e,mimeType:r[n]||"audio/unknown"}),this.logger.debug(`Added audio file: ${s.base}`)}catch(e){this.logger.error(`Failed to read audio file ${t}: ${Q(e)}`);continue}else{const e=C.statSync(t);o.push({type:"resource_link",uri:`file://${t}`,name:s.base,title:s.name,size:e.size}),this.logger.debug(`Added resource link: ${s.base}`)}}await this.protocol.sendPrompt({sessionId:this.sessionId,prompt:o})}async interrupt(){if(!this.connected||!this.protocol||!this.sessionId)throw new G("Not connected");await this.protocol.cancelSession({sessionId:this.sessionId}),this.logger.info("Sent interrupt signal")}async*receiveMessages(){if(!this.connected)throw new G("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=exports.ToolCallConfirmationOutcome.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: ${Q(e)}`);const t={type:exports.MessageType.ERROR,code:-1,message:String(Q(e))};this.messageQueue.push(t)}}processProtocolMessage(e){switch(e.type){case Wt.SESSION_UPDATE:{const{updateData:t}=e;let o,s;switch("agentId"in t&&t.agentId&&(o=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}}(o)),t.sessionUpdate){case z.PLAN:{const e=t.entries?.map(e=>({content:e.content||"",status:e.status||exports.PlanStatus.PENDING,priority:e.priority||exports.PlanPriority.MEDIUM}));return e&&e?.length>0?{type:exports.MessageType.PLAN,entries:e}:null}case z.TOOL_CALL:{const e={type:exports.MessageType.TOOL_CALL,id:t.toolCallId||"",label:t.title||"Tool",icon:{type:exports.ToolCallIconType.EMOJI,value:"🔧"},status:t.status||exports.ToolCallStatus.IN_PROGRESS,toolName:t.toolName,args:t.args};return o&&(e.agentId=o,e.agentInfo=s),this.pendingToolCalls.set(e.id,e),{...e}}case z.TOOL_CALL_UPDATE:{const e=t.toolCallId;let n;if(this.pendingToolCalls.has(e)?(n=this.pendingToolCalls.get(e),n.status=t.status||exports.ToolCallStatus.COMPLETED,t.toolName&&(n.toolName=t.toolName),!n.agentId&&o&&(n.agentId=o),!n.agentInfo&&s&&(n.agentInfo=s)):(n={type:exports.MessageType.TOOL_CALL,id:e,label:t.title||"Tool",icon:{type:exports.ToolCallIconType.EMOJI,value:"🔧"},status:t.status||exports.ToolCallStatus.COMPLETED,toolName:t.toolName},o&&(n.agentId=o,n.agentInfo=s),this.pendingToolCalls.set(e,n)),t.content&&t.content?.length>0){let e;const o=[];for(const s of t.content)"args"in s&&(e=s.args),"content"===s.type&&"text"===s.content?.type&&o.push(s.content.text||"");void 0!==e&&(n.args=e),o.length>0&&(n.output=o.join("\n"))}return{...n}}case z.USER_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t)return{type:exports.MessageType.USER,chunks:[{text:t}]}}return null}case z.AGENT_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:exports.MessageType.ASSISTANT,chunk:{text:t}};return o&&(e.agentId=o,e.agentInfo=s),e}}return null}case z.AGENT_THOUGHT_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:exports.MessageType.ASSISTANT,chunk:{thought:t}};return o&&(e.agentId=o,e.agentInfo=s),e}}}default:return null}}case Wt.RESPONSE:return"stopReason"in(e.result||{})?{type:exports.MessageType.TASK_FINISH,stopReason:e.result.stopReason}:null;case Wt.ERROR:return{type:exports.MessageType.ERROR,code:e.code||-1,message:e.error||"Unknown error"};default:return null}}}function Qt(e){let t,o=!1,s="text";if(e.startsWith("//"))o=!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:o,messageType:s,rawData:e,jsonData:t,timestamp:Date.now()}}exports.AuthenticationError=W,exports.ConnectionError=G,exports.IFlowClient=zt,exports.IFlowError=L,exports.IFlowNotInstalledError=M,exports.IFlowProcessError=F,exports.JSONDecodeError=N,exports.PermissionError=U,exports.PortNotAvailableError=k,exports.ProtocolError=H,exports.RawDataClient=class extends zt{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: ${Q(e)}`)}}async captureRawStream(){if(this.transport)try{for await(const e of this.transport.receive()){const t=Qt("string"==typeof e?e:JSON.stringify(e));this.rawQueue.push(t),this.rawHistory.push(t);const o=this.rawQueueResolvers.shift();o&&o(t)}}catch(e){this.logger.error(`Error capturing raw stream: ${Q(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=Qt("<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}`)}},exports.TimeoutError=$,exports.TransportError=D,exports.ValidationError=j,exports.query=async function(e,t,o){const s=[],n=new zt(o);await n.connect();try{await n.sendMessage(e,t);for await(const e of n.receiveMessages())if(e.type===exports.MessageType.ASSISTANT&&e.chunk.text)s.push(e.chunk.text);else if(e.type===exports.MessageType.TASK_FINISH)break}finally{await n.disconnect()}return s.join("")},exports.queryStream=async function*(e,t,o){const s=new zt(o);await s.connect();try{await s.sendMessage(e,t);for await(const e of s.receiveMessages())if(e.type===exports.MessageType.ASSISTANT&&e.chunk.text)yield e.chunk.text;else if(e.type===exports.MessageType.TASK_FINISH)break}finally{await s.disconnect()}};
|
|
1
|
+
"use strict";var e=require("fs"),t=require("path"),o=require("ws"),s=require("fs/promises"),n=require("os"),r=require("net"),i=require("child_process"),a=require("assert"),c=require("events"),l=require("buffer"),d=require("stream"),u=require("util");function p(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var s=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:function(){return e[o]}})}}),t.default=e,Object.freeze(t)}var h,f,m,g,w,y,S,x,T,E,I,v,b,P=p(e),A=p(t),C=p(s),O=p(n),_=p(r),R=p(i);class L extends Error{constructor(e,t){super(e),this.name="IFlowError",this.details=t||{}}}class $ extends L{constructor(e,t){super(e,t),this.name="TimeoutError"}}class N extends L{constructor(e,t){super(e,{rawData:t}),this.name="JSONDecodeError",this.rawData=t}}class M extends L{constructor(e,t){super(e,t),this.name="IFlowNotInstalledError"}}class F extends L{constructor(e,t){super(e,t),this.name="IFlowProcessError"}}class k extends L{constructor(e,t){super(e,t),this.name="PortNotAvailableError"}}class G extends L{constructor(e,t){super(e,t),this.name="ConnectionError"}}class D extends L{constructor(e,t){super(e,t),this.name="TransportError"}}class U extends L{constructor(e,t){super(e,t),this.name="PermissionError"}}class j extends L{constructor(e,t){super(e,t),this.name="ValidationError"}}class H extends L{constructor(e,t){super(e,t),this.name="ProtocolError"}}class W extends L{constructor(e,t){super(e,t),this.name="AuthenticationError"}}exports.LogLevel=void 0,(h=exports.LogLevel||(exports.LogLevel={}))[h.DEBUG=0]="DEBUG",h[h.INFO=1]="INFO",h[h.WARN=2]="WARN",h[h.ERROR=3]="ERROR",exports.PermissionMode=void 0,(f=exports.PermissionMode||(exports.PermissionMode={})).AUTO="auto",f.MANUAL="manual",f.SELECTIVE="selective",exports.ApprovalMode=void 0,(m=exports.ApprovalMode||(exports.ApprovalMode={})).DEFAULT="default",m.AUTO_EDIT="autoEdit",m.YOLO="yolo",m.PLAN="plan",exports.HookEventType=void 0,(g=exports.HookEventType||(exports.HookEventType={})).PRE_TOOL_USE="PreToolUse",g.POST_TOOL_USE="PostToolUse",g.STOP="Stop",g.SUBAGENT_STOP="SubagentStop",g.SET_UP_ENVIRONMENT="SetUpEnvironment",exports.PlanPriority=void 0,(w=exports.PlanPriority||(exports.PlanPriority={})).HIGH="high",w.MEDIUM="medium",w.LOW="low",exports.PlanStatus=void 0,(y=exports.PlanStatus||(exports.PlanStatus={})).PENDING="pending",y.IN_PROGRESS="in_progress",y.COMPLETED="completed",exports.StopReason=void 0,(S=exports.StopReason||(exports.StopReason={})).END_TURN="end_turn",S.MAX_TOKENS="max_tokens",S.REFUSAL="refusal",S.CANCELLED="cancelled",exports.ToolCallStatus=void 0,(x=exports.ToolCallStatus||(exports.ToolCallStatus={})).PENDING="pending",x.IN_PROGRESS="in_progress",x.COMPLETED="completed",x.FAILED="failed",exports.ToolCallContentType=void 0,(T=exports.ToolCallContentType||(exports.ToolCallContentType={})).DIFF="diff",T.MARKDOWN="markdown",exports.ToolCallConfirmationType=void 0,(E=exports.ToolCallConfirmationType||(exports.ToolCallConfirmationType={})).EDIT="edit",E.EXECUTE="execute",E.MCP="mcp",E.FETCH="fetch",E.OTHER="other",exports.ToolCallConfirmationOutcome=void 0,(I=exports.ToolCallConfirmationOutcome||(exports.ToolCallConfirmationOutcome={})).ALLOW="allow",I.ALWAYS_ALLOW="alwaysAllow",I.ALWAYS_ALLOW_TOOL="alwaysAllowTool",I.ALWAYS_ALLOW_MCP_SERVER="alwaysAllowMcpServer",I.REJECT="reject",exports.ToolCallIconType=void 0,(v=exports.ToolCallIconType||(exports.ToolCallIconType={})).URL="url",v.EMOJI="emoji",exports.MessageType=void 0,(b=exports.MessageType||(exports.MessageType={})).PLAN="plan",b.USER="user",b.ASSISTANT="assistant",b.TOOL_CALL="tool_call",b.ERROR="error",b.TASK_FINISH="task_finish";const B="2.0";var K,q,z;function Q(e){if(e instanceof Error){const t=e,o=t.details?.data?.details;return o?`${e.message}\n${o}`: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"}(K||(K={})),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"}(q||(q={})),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"}(z||(z={}));class X{constructor(e={}){const t=e.level||"INFO";this.level=exports.LogLevel[t]}debug(e){this.log(exports.LogLevel.DEBUG,e)}info(e){this.log(exports.LogLevel.INFO,e)}warn(e){this.log(exports.LogLevel.WARN,e)}error(e,t){this.log(exports.LogLevel.ERROR,e,t)}log(e,t,o){if(e<this.level)return;const s=`[${(new Date).toLocaleString("sv-SE").replace("T"," ")}] ${exports.LogLevel[e]}: ${t}${o?`\n${o.stack}`:""}`;switch(e){case exports.LogLevel.DEBUG:console.debug(s);break;case exports.LogLevel.INFO:console.info(s);break;case exports.LogLevel.WARN:console.warn(s);break;case exports.LogLevel.ERROR:console.error(s)}}}const V=new X;function J(e){return!!e&&"id"in e&&"result"in e&&null!=e.result}function Y(e){return!!e&&"id"in e&&"error"in e&&null!=e.error}function Z(e){return!!e&&"method"in e&&!("result"in e)&&!("error"in e)}class ee{constructor(e){this.requestId=0,this.initialized=!1,this.authenticated=!1,this.logger=e.logger||V,this.transport=e.transport,this.fileHandler=e.fileHandler,this.permissionMode=e.permissionMode||exports.PermissionMode.AUTO,this.autoApproveTypes=e.autoApproveTypes||["read","fetch","list"]}nextRequestId(){return++this.requestId}checkAuthenticated(){if(!this.initialized)throw new H("Protocol not initialized. Call initialize() first.");if(!this.authenticated)throw new H("Not authenticated. Call authenticate() first.")}async sendResult(e,t){const o={jsonrpc:B,id:e,result:t};await this.transport.send(o)}async sendError(e,t,o){const s={jsonrpc:B,id:e,error:{code:t,message:o}};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,o){const{timeout:s,timeoutMsg:n=`Timeout after ${s} seconds`}=o||{},r=Date.now();for await(const o of this.transport.receive()){if(o.trim().startsWith("//")){this.logger.debug(`Control message: ${o.trim()}`);continue}let i;try{i=JSON.parse(o.trim())}catch(e){this.logger.error(`Failed to parse response: ${Q(e)}`);continue}if(i.id===e){const e=t(i);if(void 0!==e)return e}if(s&&s>0&&Date.now()-r>s)throw new $(n)}}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(),o={jsonrpc:B,id:t,method:K.INITIALIZE,params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}},...e}};await this.transport.send(o),this.logger.info("Sent initialize request");const s=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new H(`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 H("Connection closed during initialization")}async authenticate(e={}){const t=e.methodId||"iflow";if(this.authenticated)return void this.logger.warn("Already authenticated");const o=this.nextRequestId(),s={jsonrpc:B,id:o,method:K.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(o,e=>{if("error"in e)throw new W(`Authentication failed: ${e.error?.message}`,e.error);const o=e.result||{};return o.methodId===t?(this.authenticated=!0,this.logger.info(`Authentication successful with method: ${o.methodId}`),!0):(this.authenticated=!0,this.logger.warn(`Unexpected methodId in response: ${o.methodId} (expected ${t})`),!0)},{timeout:1e4,timeoutMsg:"Authentication timeout after 10 seconds"}))throw new W("Connection closed during authentication")}async createSession(e={}){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_NEW,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(o),this.logger.info(`Sent session/new request with cwd: ${e.cwd}`);const s=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new H(`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 H(`Invalid session/new response: ${JSON.stringify(t)}`)},{timeout:1e4,timeoutMsg:"Session creation timeout after 10 seconds"});if(s)return s;throw new H("Connection closed while waiting for session/new response")}async loadSession(e){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_LOAD,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(o),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 H("session/load is not supported by the current iFlow version. Use session/new to create a new session instead.",t.error);throw new H(`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 H("Connection closed while waiting for session/load response")}async sendPrompt(e){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_PROMPT,params:e};return await this.transport.send(o),this.logger.info(`Sent prompt with ${e.prompt.length} content blocks`),t}async cancelSession(e){this.checkAuthenticated();const t=this.nextRequestId(),o={jsonrpc:B,id:t,method:K.SESSION_CANCEL,params:e};await this.transport.send(o),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: ${Q(t)}`),new N("Invalid JSON received",e)}Z(t)?yield await this.handleClientMessage(t):J(t)?yield{type:"response",id:t.id,result:t.result}:Y(t)&&(yield{type:"error",code:t.error.code,error:t.error.message})}}async handleClientMessage(e){const{method:t}=e;switch(t){case q.FS_READ_TEXT_FILE:return await this.handleReadTextFile(e);case q.FS_WRITE_TEXT_FILE:return await this.handleWriteTextFile(e);case q.SESSION_UPDATE:return await this.handleSessionUpdate(e);case q.SESSION_REQUEST_PERMISSION:return await this.handleRequestPermission(e);case q.PUSH_TOOL_CALL:return await this.handlePushToolCall(e);case q.UPDATE_TOOL_CALL:return await this.handleUpdateToolCall(e);case q.NOTIFY_TASK_FINISH:return await this.handleNotifyTaskFinish(e);default:return await this.handleUnknownMessage(e)}}async handleReadTextFile(e){const{id:t,method:o,params:s}=e,{path:n,limit:r,line:i}=s||{};let a;if(this.logger.info(`fs/read_text_file request for: ${n}`),!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:o}}try{a=await this.fileHandler.readFile(n,i,r)}catch(e){const s=Q(e);return this.logger.error(`Error reading file ${n}: ${s}`),void 0!==t&&await this.sendError(t,-32603,s),{type:"error",code:-32603,error:s,method:o}}return void 0!==t&&await this.sendResult(t,{content:a}),{type:"file_read",path:n,content:a}}async handleWriteTextFile(e){const{id:t,method:o,params:s}=e,{path:n,content:r}=s||{};if(this.logger.info(`fs/write_text_file request for: ${n}`),!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:o}}try{await this.fileHandler.writeFile(n,r)}catch(e){const s=Q(e);return this.logger.error(`Error writing file ${n}: ${s}`),void 0!==t&&await this.sendError(t,-32603,s),{type:"error",code:-32603,error:s,method:o}}return void 0!==t&&await this.sendResult(t,{success:!0}),{type:"file_write",path:n,content:r}}async handleSessionUpdate(e){const{params:t}=e,{sessionId:o,update:s}=t;return{type:"session_update",sessionId:o,updateData:s}}async handleRequestPermission(e){const{id:t,params:o}=e,s=o.toolCall||{},n=o.options||[];let r,i;if(r=this.permissionMode===exports.PermissionMode.AUTO||this.permissionMode!==exports.PermissionMode.MANUAL&&this.autoApproveTypes.includes(s.type||""),r){let e;for(const t of n){const o=t.optionId||"";if("proceed_once"===o){e=o;break}"proceed_always"===o&&(e=o)}!e&&n.length>0&&(e=n[0].optionId||"proceed_once"),i={outcome:{outcome:"selected",optionId:e}}}else i={outcome:{outcome:"cancelled"}};return void 0!==t&&await this.sendResult(t,i),this.logger.info(`Permission request for tool '${s.title||"unknown"}' - Response: ${i.outcome.outcome}`),{type:"tool_confirmation",params:o,response:i}}async handlePushToolCall(e){const{id:t,params:o}=e,s=`tool_${this.nextRequestId()}`,n={id:s};return void 0!==t&&await this.sendResult(t,n),{type:"tool_call",id:s,params:o}}async handleUpdateToolCall(e){const{id:t,params:o}=e;return void 0!==t&&await this.sendResult(t,null),{type:"tool_update",params:o}}async handleNotifyTaskFinish(e){const{id:t,params:o}=e;return void 0!==t&&await this.sendResult(t,null),{type:"task_finish",params:o}}async handleUnknownMessage(e){const{id:t,method:o,params:s}=e;return this.logger.warn(`Unknown method: ${o}`),void 0!==t&&await this.sendError(t,-32601,"Method not found"),{type:"unknown",method:o,params:s}}}class te{constructor(e){this.ws=null,this.connected=!1,this.url=e.url,this.logger=e.logger||V,this.timeout=e.timeout||3e5}get isConnected(){return!!this.ws&&this.connected}checkConnected(){if(!this.isConnected)throw new G("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 $(`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,o)=>{clearTimeout(n),this.connected=!1,t(new Error(`${o} (code: ${e})`))})})}catch(e){if(e instanceof $)throw e;throw new G(`Failed to connect to ${this.url}: ${Q(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: ${Q(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,o)=>{this.ws.send(t,s=>{s?o(s):(this.logger.debug(`Sent message: ${t}`),e())})})}catch(e){throw this.connected=!1,new D(`Failed to send message: ${Q(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 G&&e.details.isClosed){this.logger.info("Connection closed");break}throw new D(`Failed to receive message: ${Q(e)}`)}}receiveRawData(){return new Promise((e,t)=>{if(!this.isConnected)return void t(new G("Not connected"));const o=()=>{this.ws&&(this.ws.off("close",s),this.ws.off("error",n),this.ws.off("message",r))},s=()=>{o(),this.connected=!1,t(new G("Connection closed",{isClosed:!0}))},n=e=>{o(),this.connected=!1,t(e)},r=t=>{o(),e(t.toString())};this.ws&&(this.ws.on("close",s),this.ws.on("error",n),this.ws.on("message",r))})}}class oe{constructor(e={}){this.cwd=e.cwd||process.cwd(),this.logger=e.logger||V,this.readOnly=e.readOnly||!1,this.maxFileSize=e.maxFileSize||10485760,e.allowedDirs?this.allowedDirs=new Set(e.allowedDirs.map(e=>A.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=A.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(e,t,o){if(!this.isPathAllowed(e))throw new U(`Access denied: ${e}`);const s=A.resolve(this.cwd,e);try{if(!P.existsSync(s))throw new j(`File not found: ${e}`);try{await C.access(s,P.constants.R_OK)}catch{throw new U(`Permission denied: ${e}`)}const n=await C.stat(s);if(!n.isFile())throw new j(`Not a file: ${e}`);if(n.size>this.maxFileSize)throw new j(`File too large: ${n.size} bytes (max: ${this.maxFileSize})`);const r=await C.readFile(s,"utf-8");if(void 0!==t||void 0!==o){const s=r.split("\n"),n=t?t-1:0,i=o?n+o:s.length,a=Math.max(0,n),c=Math.min(s.length,i);return this.logger.debug(`Read ${c-a} lines from ${e}`),s.slice(a,c).join("\n")}return this.logger.debug(`Read ${r.length} bytes from ${e}`),r}catch(e){if(e instanceof j||e instanceof U)throw e;throw new j(`Failed to read file: ${Q(e)}`)}}async writeFile(e,t){if(this.readOnly)throw new U("File system is in read-only mode");if(!this.isPathAllowed(e))throw new U(`Access denied: ${e}`);const o=A.resolve(this.cwd,e);try{await C.mkdir(A.dirname(o),{recursive:!0}),await C.writeFile(o,t,"utf-8"),this.logger.debug(`Wrote ${t.length} bytes to ${e}`)}catch(e){throw new j(`Failed to write file: ${Q(e)}`)}}async addAllowedDir(e){const t=A.resolve(this.cwd,e);try{if(!P.existsSync(t))throw new j(`Directory does not exist: ${t}`);if(!(await C.stat(t)).isDirectory())throw new j(`Not a directory: ${t}`);this.allowedDirs.add(t),this.logger.info(`Added allowed directory: ${t}`)}catch(e){if(e instanceof j)throw e;throw new j(`Failed to add ${t} as allowed directory: ${Q(e)}`)}}removeAllowedDir(e){const t=A.resolve(this.cwd,e);this.allowedDirs.delete(t),this.logger.info(`Removed allowed directory: ${t}`)}}var se="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ne(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var re,ie,ae,ce,le,de,ue,pe,he={exports:{}},fe={exports:{}};function me(){if(ie)return re;ie=1,re=s,s.sync=function(e,s){return o(t.statSync(e),e,s)};var t=e;function o(e,t,o){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var o=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!o)return!0;if(-1!==(o=o.split(";")).indexOf(""))return!0;for(var s=0;s<o.length;s++){var n=o[s].toLowerCase();if(n&&e.substr(-n.length).toLowerCase()===n)return!0}return!1}(t,o)}function s(e,s,n){t.stat(e,function(t,r){n(t,!t&&o(r,e,s))})}return re}function ge(){if(ce)return ae;ce=1,ae=o,o.sync=function(e,o){return s(t.statSync(e),o)};var t=e;function o(e,o,n){t.stat(e,function(e,t){n(e,!e&&s(t,o))})}function s(e,t){return e.isFile()&&function(e,t){var o=e.mode,s=e.uid,n=e.gid,r=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=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 o&l||o&c&&n===i||o&a&&s===r||o&d&&0===r}(e,t)}return ae}function we(){if(pe)return ue;pe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,o=t,s=e?";":":",n=function(){if(de)return le;var e;function t(o,s,n){if("function"==typeof s&&(n=s,s={}),!n){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,n){t(o,s||{},function(t,o){t?n(t):e(o)})})}e(o,s||{},function(e,t){e&&("EACCES"===e.code||s&&s.ignoreErrors)&&(e=null,t=!1),n(e,t)})}return de=1,e="win32"===process.platform||se.TESTING_WINDOWS?me():ge(),le=t,t.sync=function(t,o){try{return e.sync(t,o||{})}catch(e){if(o&&o.ignoreErrors||"EACCES"===e.code)return!1;throw e}},le}(),r=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,o)=>{const n=o.colon||s,r=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(o.path||process.env.PATH||"").split(n)],i=e?o.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(n):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:r,pathExt:a,pathExtExe:i}},a=(e,t,s)=>{"function"==typeof t&&(s=t,t={}),t||(t={});const{pathEnv:a,pathExt:c,pathExtExe:l}=i(e,t),d=[],u=s=>new Promise((n,i)=>{if(s===a.length)return t.all&&d.length?n(d):i(r(e));const c=a[s],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=o.join(l,e),h=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;n(p(h,s,0))}),p=(e,o,s)=>new Promise((r,i)=>{if(s===c.length)return r(u(o+1));const a=c[s];n(e+a,{pathExt:l},(n,i)=>{if(!n&&i){if(!t.all)return r(e+a);d.push(e+a)}return r(p(e,o,s+1))})});return s?u(0).then(e=>s(null,e),s):u(0)};return ue=a,a.sync=(e,t)=>{t=t||{};const{pathEnv:s,pathExt:a,pathExtExe:c}=i(e,t),l=[];for(let r=0;r<s.length;r++){const i=s[r],d=/^".*"$/.test(i)?i.slice(1,-1):i,u=o.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<a.length;e++){const o=p+a[e];try{if(n.sync(o,{pathExt:c})){if(!t.all)return o;l.push(o)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw r(e)},ue}var ye,Se,xe,Te={exports:{}};function Ee(){if(ye)return Te.exports;ye=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 Te.exports=e,Te.exports.default=e,Te.exports}var Ie,ve,be,Pe,Ae,Ce,Oe,_e,Re,Le,$e,Ne,Me,Fe,ke={};function Ge(){return be?ve:(be=1,ve=/^#!(.*)/)}function De(){if(Ae)return Pe;Ae=1;const e=Ge();return Pe=(t="")=>{const o=t.match(e);if(!o)return null;const[s,n]=o[0].replace(/#! ?/,"").split(" "),r=s.split("/").pop();return"env"===r?n:n?`${r} ${n}`:r},Pe}function Ue(){if(Re)return _e;Re=1;const o=t,s=function(){if(xe)return Se;xe=1;const e=t,o=we(),s=Ee();function n(t,n){const r=t.options.env||process.env,i=process.cwd(),a=null!=t.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(t.options.cwd)}catch(e){}let l;try{l=o.sync(t.command,{path:r[s({env:r})],pathExt:n?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?t.options.cwd:"",l)),l}return Se=function(e){return n(e)||n(e,!0)}}(),n=function(){if(Ie)return ke;Ie=1;const e=/([()\][%!^"`<>&|;, *?])/g;return ke.command=function(t){return t.replace(e,"^$1")},ke.argument=function(t,o){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),o&&(t=t.replace(e,"^$1")),t},ke}(),r=function(){if(Oe)return Ce;Oe=1;const t=e,o=De();return Ce=function(e){const s=Buffer.alloc(150);let n;try{n=t.openSync(e,"r"),t.readSync(n,s,0,150,0),t.closeSync(n)}catch(e){}return o(s.toString())},Ce}(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){if(!i)return e;const t=function(e){e.file=s(e);const t=e.file&&r(e.file);return t?(e.args.unshift(e.file),e.command=t,s(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const s=c.test(t);e.command=o.normalize(e.command),e.command=n.command(e.command),e.args=e.args.map(e=>n.argument(e,s));const r=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${r}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}return _e=function(e,t,o){t&&!Array.isArray(t)&&(o=t,t=null);const s={command:e,args:t=t?t.slice(0):[],options:o=Object.assign({},o),file:void 0,original:{command:e,args:t}};return o.shell?s:l(s)},_e}function je(){if($e)return Le;$e=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 o(o,s){return e&&1===o&&!s.file?t(s.original,"spawn"):null}return Le={hookChildProcess:function(t,s){if(!e)return;const n=t.emit;t.emit=function(e,r){if("exit"===e){const e=o(r,s);if(e)return n.call(t,"error",e)}return n.apply(t,arguments)}},verifyENOENT:o,verifyENOENTSync:function(o,s){return e&&1===o&&!s.file?t(s.original,"spawnSync"):null},notFoundError:t},Le}function He(){if(Ne)return fe.exports;Ne=1;const e=i,t=Ue(),o=je();function s(s,n,r){const i=t(s,n,r),a=e.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}return fe.exports=s,fe.exports.spawn=s,fe.exports.sync=function(s,n,r){const i=t(s,n,r),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},fe.exports._parse=t,fe.exports._enoent=o,fe.exports}function We(){return Fe?Me:(Fe=1,Me=e=>{const t="string"==typeof e?"\n":"\n".charCodeAt(),o="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,e.length-1)),e[e.length-1]===o&&(e=e.slice(0,e.length-1)),e})}var Be,Ke={exports:{}};function qe(){return Be||(Be=1,function(e){const o=t,s=Ee(),n=e=>{let t;e={cwd:process.cwd(),path:process.env[s()],execPath:process.execPath,...e};let n=o.resolve(e.cwd);const r=[];for(;t!==n;)r.push(o.join(n,"node_modules/.bin")),t=n,n=o.resolve(n,"..");const i=o.resolve(e.cwd,e.execPath,"..");return r.push(i),r.concat(e.path).join(o.delimiter)};e.exports=n,e.exports.default=n,e.exports.env=t=>{const o={...(t={env:process.env,...t}).env},n=s({env:o});return t.path=o[n],o[n]=e.exports(t),o}}(Ke)),Ke.exports}var ze,Qe,Xe={exports:{}},Ve={exports:{}};function Je(){if(ze)return Ve.exports;ze=1;const e=(e,t)=>{for(const o of Reflect.ownKeys(t))Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(t,o));return e};return Ve.exports=e,Ve.exports.default=e,Ve.exports}function Ye(){if(Qe)return Xe.exports;Qe=1;const e=Je(),t=new WeakMap,o=(o,s={})=>{if("function"!=typeof o)throw new TypeError("Expected a function");let n,r=0;const i=o.displayName||o.name||"<anonymous>",a=function(...e){if(t.set(a,++r),1===r)n=o.apply(this,e),o=null;else if(!0===s.throw)throw new Error(`Function \`${i}\` can only be called once`);return n};return e(a,o),t.set(a,r),a};return Xe.exports=o,Xe.exports.default=o,Xe.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)},Xe.exports}var Ze,et={},tt={},ot={};var st,nt,rt,it,at,ct={};function lt(){if(st)return ct;st=1,Object.defineProperty(ct,"__esModule",{value:!0}),ct.SIGRTMAX=ct.getRealtimeSignals=void 0;ct.getRealtimeSignals=function(){const s=o-t+1;return Array.from({length:s},e)};const e=function(e,o){return{name:`SIGRT${o+1}`,number:t+o,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},t=34,o=64;return ct.SIGRTMAX=o,ct}function dt(){if(nt)return tt;nt=1,Object.defineProperty(tt,"__esModule",{value:!0}),tt.getSignals=void 0;var e=n,t=(Ze||(Ze=1,Object.defineProperty(ot,"__esModule",{value:!0}),ot.SIGNALS=void 0,ot.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"}]),ot),o=lt();tt.getSignals=function(){const e=(0,o.getRealtimeSignals)();return[...t.SIGNALS,...e].map(s)};const s=function({name:t,number:o,description:s,action:n,forced:r=!1,standard:i}){const{signals:{[t]:a}}=e.constants,c=void 0!==a;return{name:t,number:c?a:o,description:s,supported:c,action:n,forced:r,standard:i}};return tt}function ut(){if(at)return it;at=1;const{signalsByName:e}=function(){if(rt)return et;rt=1,Object.defineProperty(et,"__esModule",{value:!0}),et.signalsByNumber=et.signalsByName=void 0;var e=n,t=dt(),o=lt();const s=function(e,{name:t,number:o,description:s,supported:n,action:r,forced:i,standard:a}){return{...e,[t]:{name:t,number:o,description:s,supported:n,action:r,forced:i,standard:a}}},r=(0,t.getSignals)().reduce(s,{});et.signalsByName=r;const i=function(e,t){const o=a(e,t);if(void 0===o)return{};const{name:s,description:n,supported:r,action:i,forced:c,standard:l}=o;return{[e]:{name:s,number:e,description:n,supported:r,action:i,forced:c,standard:l}}},a=function(t,o){const s=o.find(({name:o})=>e.constants.signals[o]===t);return void 0!==s?s:o.find(e=>e.number===t)},c=function(){const e=(0,t.getSignals)(),s=o.SIGRTMAX+1,n=Array.from({length:s},(t,o)=>i(o,e));return Object.assign({},...n)}();return et.signalsByNumber=c,et}();return it=({stdout:t,stderr:o,all:s,error:n,signal:r,exitCode:i,command:a,escapedCommand:c,timedOut:l,isCanceled:d,killed:u,parsed:{options:{timeout:p}}})=>{i=null===i?void 0:i;const h=void 0===(r=null===r?void 0:r)?void 0:e[r].description,f=(({timedOut:e,timeout:t,errorCode:o,signal:s,signalDescription:n,exitCode:r,isCanceled:i})=>e?`timed out after ${t} milliseconds`:i?"was canceled":void 0!==o?`failed with ${o}`:void 0!==s?`was killed with ${s} (${n})`:void 0!==r?`failed with exit code ${r}`:"failed")({timedOut:l,timeout:p,errorCode:n&&n.code,signal:r,signalDescription:h,exitCode:i,isCanceled:d}),m=`Command ${f}: ${a}`,g="[object Error]"===Object.prototype.toString.call(n),w=g?`${m}\n${n.message}`:m,y=[w,o,t].filter(Boolean).join("\n");return g?(n.originalMessage=n.message,n.message=y):n=new Error(y),n.shortMessage=w,n.command=a,n.escapedCommand=c,n.exitCode=i,n.signal=r,n.signalDescription=h,n.stdout=t,n.stderr=o,void 0!==s&&(n.all=s),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(l),n.isCanceled=d,n.killed=u&&!l,n},it}var pt,ht={exports:{}};function ft(){if(pt)return ht.exports;pt=1;const e=["stdin","stdout","stderr"],t=t=>{if(!t)return;const{stdio:o}=t;if(void 0===o)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 o)return o;if(!Array.isArray(o))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof o}\``);const s=Math.max(o.length,e.length);return Array.from({length:s},(e,t)=>o[t])};return ht.exports=t,ht.exports.node=e=>{const o=t(e);return"ipc"===o?"ipc":void 0===o||"string"==typeof o?[o,o,o,"ipc"]:o.includes("ipc")?o:[...o,"ipc"]},ht.exports}var mt,gt,wt,yt,St,xt,Tt={exports:{}},Et={exports:{}};function It(){return mt||(mt=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 vt(){if(yt)return wt;yt=1;const e=n,t=function(){if(gt)return Tt.exports;gt=1;var e=se.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 o,s=a,n=It(),r=/^win/i.test(e.platform),i=c;"function"!=typeof i&&(i=i.EventEmitter),e.__signal_exit_emitter__?o=e.__signal_exit_emitter__:((o=e.__signal_exit_emitter__=new i).count=0,o.emitted={}),o.infinite||(o.setMaxListeners(1/0),o.infinite=!0),Tt.exports=function(e,n){if(!t(se.process))return function(){};s.equal(typeof e,"function","a callback must be provided for exit handler"),!1===p&&h();var r="exit";return n&&n.alwaysLast&&(r="afterexit"),o.on(r,e),function(){o.removeListener(r,e),0===o.listeners("exit").length&&0===o.listeners("afterexit").length&&l()}};var l=function(){p&&t(se.process)&&(p=!1,n.forEach(function(t){try{e.removeListener(t,u[t])}catch(e){}}),e.emit=g,e.reallyExit=f,o.count-=1)};Tt.exports.unload=l;var d=function(e,t,s){o.emitted[e]||(o.emitted[e]=!0,o.emit(e,t,s))},u={};n.forEach(function(s){u[s]=function(){t(se.process)&&e.listeners(s).length===o.count&&(l(),d("exit",null,s),d("afterexit",null,s),r&&"SIGHUP"===s&&(s="SIGINT"),e.kill(e.pid,s))}}),Tt.exports.signals=function(){return n};var p=!1,h=function(){!p&&t(se.process)&&(p=!0,o.count+=1,n=n.filter(function(t){try{return e.on(t,u[t]),!0}catch(e){return!1}}),e.emit=w,e.reallyExit=m)};Tt.exports.load=h;var f=e.reallyExit,m=function(o){t(se.process)&&(e.exitCode=o||0,d("exit",e.exitCode,null),d("afterexit",e.exitCode,null),f.call(e,e.exitCode))},g=e.emit,w=function(o,s){if("exit"===o&&t(se.process)){void 0!==s&&(e.exitCode=s);var n=g.apply(this,arguments);return d("exit",e.exitCode,null),d("afterexit",e.exitCode,null),n}return g.apply(this,arguments)}}else Tt.exports=function(){return function(){}};return Tt.exports}(),o=(e,t,o,n)=>{if(!s(t,o,n))return;const r=i(o),a=setTimeout(()=>{e("SIGKILL")},r);a.unref&&a.unref()},s=(e,{forceKillAfterTimeout:t},o)=>r(e)&&!1!==t&&o,r=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 wt={spawnedKill:(e,t="SIGTERM",s={})=>{const n=e(t);return o(e,t,s,n),n},spawnedCancel:(e,t)=>{e.kill()&&(t.isCanceled=!0)},setupTimeout:(e,{timeout:t,killSignal:o="SIGTERM"},s)=>{if(0===t||void 0===t)return s;let n;const r=new Promise((s,r)=>{n=setTimeout(()=>{((e,t,o)=>{e.kill(t),o(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))})(e,o,r)},t)}),i=s.finally(()=>{clearTimeout(n)});return Promise.race([r,i])},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:o,detached:s},n)=>{if(!o||s)return n;const r=t(()=>{e.kill()});return n.finally(()=>{r()})}}}var bt,Pt,At,Ct,Ot,_t,Rt,Lt,$t,Nt,Mt,Ft,kt={exports:{}};function Gt(){if(Pt)return bt;Pt=1;const{PassThrough:e}=d;return bt=t=>{t={...t};const{array:o}=t;let{encoding:s}=t;const n="buffer"===s;let r=!1;o?r=!(s||n):s=s||"utf8",n&&(s=null);const i=new e({objectMode:r});s&&i.setEncoding(s);let a=0;const c=[];return i.on("data",e=>{c.push(e),r?a=c.length:a+=e.length}),i.getBufferedValue=()=>o?c:n?Buffer.concat(c,a):c.join(""),i.getBufferedLength=()=>a,i},bt}function Dt(){if(At)return kt.exports;At=1;const{constants:e}=l,t=d,{promisify:o}=u,s=Gt(),n=o(t.pipeline);class r extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function i(t,o){if(!t)throw new Error("Expected a stream");o={maxBuffer:1/0,...o};const{maxBuffer:i}=o,a=s(o);return await new Promise((o,s)=>{const c=t=>{t&&a.getBufferedLength()<=e.MAX_LENGTH&&(t.bufferedData=a.getBufferedValue()),s(t)};(async()=>{try{await n(t,a),o()}catch(e){c(e)}})(),a.on("data",()=>{a.getBufferedLength()>i&&c(new r)})}),a.getBufferedValue()}return kt.exports=i,kt.exports.buffer=(e,t)=>i(e,{...t,encoding:"buffer"}),kt.exports.array=(e,t)=>i(e,{...t,array:!0}),kt.exports.MaxBufferError=r,kt.exports}function Ut(){if(Ot)return Ct;Ot=1;const{PassThrough:e}=d;return Ct=function(){var t=[],o=new e({objectMode:!0});return o.setMaxListeners(0),o.add=s,o.isEmpty=function(){return 0==t.length},o.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(s),o;function s(e){return Array.isArray(e)?(e.forEach(s),this):(t.push(e),e.once("end",n.bind(null,e)),e.once("error",o.emit.bind(o,"error")),e.pipe(o,{end:!1}),this)}function n(e){!(t=t.filter(function(t){return t!==e})).length&&o.readable&&o.end()}},Ct}function jt(){if(Rt)return _t;Rt=1;const e=function(){if(xt)return St;xt=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,St=e}(),t=Dt(),o=Ut(),s=async(e,t)=>{if(e){e.destroy();try{return await t}catch(e){return e.bufferedData}}},n=(e,{encoding:o,buffer:s,maxBuffer:n})=>{if(e&&s)return o?t(e,{encoding:o,maxBuffer:n}):t.buffer(e,{maxBuffer:n})};return _t={handleInput:(t,o)=>{void 0!==o&&void 0!==t.stdin&&(e(o)?o.pipe(t.stdin):t.stdin.end(o))},makeAllStream:(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const s=o();return e.stdout&&s.add(e.stdout),e.stderr&&s.add(e.stderr),s},getSpawnedResult:async({stdout:e,stderr:t,all:o},{encoding:r,buffer:i,maxBuffer:a},c)=>{const l=n(e,{encoding:r,buffer:i,maxBuffer:a}),d=n(t,{encoding:r,buffer:i,maxBuffer:a}),u=n(o,{encoding:r,buffer:i,maxBuffer:2*a});try{return await Promise.all([c,l,d,u])}catch(n){return Promise.all([{error:n,signal:n.signal,timedOut:n.timedOut},s(e,l),s(t,d),s(o,u)])}},validateInputSync:({input:t})=>{if(e(t))throw new TypeError("The `input` option cannot be a stream in sync mode")}},_t}function Ht(){if(Mt)return Nt;Mt=1;const e=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],t=/^[\w.-]+$/,o=/"/g,s=/ +/g;return Nt={joinCommand:(t,o)=>e(t,o).join(" "),getEscapedCommand:(s,n)=>e(s,n).map(e=>(e=>"string"!=typeof e||t.test(e)?e:`"${e.replace(o,'\\"')}"`)(e)).join(" "),parseCommand:e=>{const t=[];for(const o of e.trim().split(s)){const e=t[t.length-1];e&&e.endsWith("\\")?t[t.length-1]=`${e.slice(0,-1)} ${o}`:t.push(o)}return t}}}var Wt,Bt=function(){if(Ft)return he.exports;Ft=1;const e=t,o=i,s=He(),n=We(),r=qe(),a=Ye(),c=ut(),l=ft(),{spawnedKill:d,spawnedCancel:u,setupTimeout:p,validateTimeout:h,setExitHandler:f}=vt(),{handleInput:m,getSpawnedResult:g,makeAllStream:w,validateInputSync:y}=jt(),{mergePromise:S,getSpawnedPromise:x}=function(){if($t)return Lt;$t=1;const e=(async()=>{})().constructor.prototype,t=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(e,t)]);return Lt={mergePromise:(e,o)=>{for(const[s,n]of t){const t="function"==typeof o?(...e)=>Reflect.apply(n.value,o(),e):n.value.bind(o);Reflect.defineProperty(e,s,{...n,value:t})}return e},getSpawnedPromise:e=>new Promise((t,o)=>{e.on("exit",(e,o)=>{t({exitCode:e,signal:o})}),e.on("error",e=>{o(e)}),e.stdin&&e.stdin.on("error",e=>{o(e)})})},Lt}(),{joinCommand:T,parseCommand:E,getEscapedCommand:I}=Ht(),v=(t,o,n={})=>{const i=s._parse(t,o,n);return t=i.command,o=i.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=i.options).cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...n}).env=(({env:e,extendEnv:t,preferLocal:o,localDir:s,execPath:n})=>{const i=t?{...process.env,...e}:e;return o?r.env({env:i,cwd:s,execPath:n}):i})(n),n.stdio=l(n),"win32"===process.platform&&"cmd"===e.basename(t,".exe")&&o.unshift("/q"),{file:t,args:o,options:n,parsed:i}},b=(e,t,o)=>"string"==typeof t||Buffer.isBuffer(t)?e.stripFinalNewline?n(t):t:void 0===o?void 0:"",P=(e,t,s)=>{const n=v(e,t,s),r=T(e,t),i=I(e,t);let l;h(n.options);try{l=o.spawn(n.file,n.args,n.options)}catch(e){const t=new o.ChildProcess,s=Promise.reject(c({error:e,stdout:"",stderr:"",all:"",command:r,escapedCommand:i,parsed:n,timedOut:!1,isCanceled:!1,killed:!1}));return S(t,s)}const y=x(l),E=p(l,n.options,y),P=f(l,n.options,E),A={isCanceled:!1};l.kill=d.bind(null,l.kill.bind(l)),l.cancel=u.bind(null,l,A);const C=a(async()=>{const[{error:e,exitCode:t,signal:o,timedOut:s},a,d,u]=await g(l,n.options,P),p=b(n.options,a),h=b(n.options,d),f=b(n.options,u);if(e||0!==t||null!==o){const a=c({error:e,exitCode:t,signal:o,stdout:p,stderr:h,all:f,command:r,escapedCommand:i,parsed:n,timedOut:s,isCanceled:A.isCanceled,killed:l.killed});if(!n.options.reject)return a;throw a}return{command:r,escapedCommand:i,exitCode:0,stdout:p,stderr:h,all:f,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return m(l,n.options.input),l.all=w(l,n.options),S(l,C)};return he.exports=P,he.exports.sync=(e,t,s)=>{const n=v(e,t,s),r=T(e,t),i=I(e,t);let a;y(n.options);try{a=o.spawnSync(n.file,n.args,n.options)}catch(e){throw c({error:e,stdout:"",stderr:"",all:"",command:r,escapedCommand:i,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=b(n.options,a.stdout,a.error),d=b(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=c({stdout:l,stderr:d,error:a.error,signal:a.signal,exitCode:a.status,command:r,escapedCommand:i,parsed:n,timedOut:a.error&&"ETIMEDOUT"===a.error.code,isCanceled:!1,killed:null!==a.signal});if(!n.options.reject)return e;throw e}return{command:r,escapedCommand:i,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},he.exports.command=(e,t)=>{const[o,...s]=E(e);return P(o,s,t)},he.exports.commandSync=(e,t)=>{const[o,...s]=E(e);return P.sync(o,s,t)},he.exports.node=(e,t,o={})=>{t&&!Array.isArray(t)&&"object"==typeof t&&(o=t,t=[]);const s=l.node(o),n=process.execArgv.filter(e=>!e.startsWith("--inspect")),{nodePath:r=process.execPath,nodeOptions:i=n}=o;return P(r,[...i,e,...Array.isArray(t)?t:[]],{...o,stdin:void 0,stdout:void 0,stderr:void 0,stdio:s,shell:!1})},he.exports}(),Kt=ne(Bt);class qt{constructor(e={}){this.port=null,this.process=null,this.iflowPath=null,this.exitHandler=null,this.isCleaningUp=!1,this.logger=e.logger||V,this.startPort=e.startPort||8090}get url(){if(!this.port)throw new F("iFlow process not started");return`ws://localhost:${this.port}/acp`}isRunning(){return!!this.process&&!this.process.killed&&null===this.process.exitCode}isWindows(){return"win32"===O.platform()}which(e){try{const t=this.isWindows()?"where":"which",o=R.execSync(`${t} ${e}`,{encoding:"utf-8",windowsHide:!0});return o.trim().split("\n")[0].trim()||null}catch{return null}}fileExists(e){try{return P.existsSync(e)&&P.statSync(e).isFile()}catch{return!1}}getFallbackLocations(){const e=O.homedir(),t=O.platform();if(this.isWindows())return[A.join(e,"AppData","Roaming","npm","iflow.cmd"),A.join(e,"AppData","Local","npm","iflow.cmd"),A.join(e,"AppData","Roaming","npm","iflow.exe"),A.join("C:","Program Files","nodejs","iflow.cmd"),A.join("C:","Program Files (x86)","nodejs","iflow.cmd"),A.join(e,".npm-global","iflow.cmd"),A.join(e,"node_modules",".bin","iflow.cmd")];{const o=["/usr/local/bin/iflow",A.join(e,".npm-global","bin","iflow"),A.join(e,".local","bin","iflow"),A.join(e,"node_modules",".bin","iflow"),A.join(e,".yarn","bin","iflow"),A.join(e,".config","yarn","global","node_modules",".bin","iflow"),A.join(e,".local","share","pnpm","iflow"),"/usr/bin/iflow"];return"darwin"===t&&"arm64"===O.arch()&&o.unshift("/opt/homebrew/bin/iflow"),o}}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 o=null!==this.which("npm"),s=null!==this.which("node");let n;throw n=this.isWindows()?o||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 M(n)}isPortAvailable(e,t=1e3){return new Promise(o=>{const s=_.createServer(),n=setTimeout(()=>{s.close(),o(!1)},t);s.listen(e,"localhost",()=>{clearTimeout(n),s.once("close",()=>{o(!0)}),s.close()}),s.once("error",()=>{clearTimeout(n),o(!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 k(`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=Kt(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 F(`Failed to start iFlow process: ${Q(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{R.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:qt.TASKKILL_TIMEOUT_EXIT_HANDLER,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill failed: ${Q(e)}`)}else this.process.kill("SIGKILL")}catch(e){this.logger.debug(`Error during process cleanup: ${Q(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{R.execSync(`taskkill /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:3e3,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill (graceful shutdown) failed: ${Q(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{R.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:qt.TASKKILL_TIMEOUT_STOP,stdio:"ignore"})}catch(e){this.logger.warn(`taskkill /F /T failed, process may have already exited or is inaccessible: ${Q(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: ${Q(e)}`)}finally{this.port=null,this.process=null}}}async onSpawn(e=5e3){return new Promise((t,o)=>{if(!this.process)return void o(new Error("Process not initialized"));const s=setTimeout(()=>{o(new Error(`Process spawn timeout after ${e}ms`))},e);this.process.once("spawn",()=>{clearTimeout(s),setTimeout(t,2e3)})})}}qt.TASKKILL_TIMEOUT_EXIT_HANDLER=3e3,qt.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"}(Wt||(Wt={}));class zt{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:exports.PermissionMode.AUTO,autoApproveTypes:["read","fetch","list"],authMethodId:"iflow",autoStartProcess:!0,processStartPort:8090,...e},this.logger=new X({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 te({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 qt({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 M?(this.logger.error("iFlow not installed"),M):(this.logger.error(`Failed to start iFlow process: ${Q(e)}`),new G(`Failed to start iFlow process: ${Q(e)}`))}}}let e=null;this.options.fileAccess&&(e=new oe({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 te({url:this.options.url,logger:this.logger,timeout:this.options.timeout}),this.protocol=new ee({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 G(`Failed to connect: ${Q(e)}`)}}async loadSession(e){if(!this.connected||!this.protocol)throw new G("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(e,t){if(!this.connected||!this.protocol||!this.sessionId)throw new G("Not connected. Call connect() first.");const o=[{type:"text",text:e}];if(t?.length)for(const e of t){const t=A.resolve(this.options.cwd||process.cwd(),e),s=A.parse(e);if(!P.existsSync(t)){this.logger.warn(`File not found, skipping: ${t}`);continue}const n=s.ext.toLowerCase();if([".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg"].includes(n))try{const e=P.readFileSync(t).toString("base64"),r={".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:e,mimeType:r[n]||"image/unknown"}),this.logger.debug(`Added image file: ${s.base}`)}catch(e){this.logger.error(`Failed to read image file ${t}: ${Q(e)}`);continue}else if([".mp3",".wav",".m4a",".ogg",".flac"].includes(n))try{const e=P.readFileSync(t).toString("base64"),r={".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".flac":"audio/flac"};o.push({type:"audio",data:e,mimeType:r[n]||"audio/unknown"}),this.logger.debug(`Added audio file: ${s.base}`)}catch(e){this.logger.error(`Failed to read audio file ${t}: ${Q(e)}`);continue}else{const e=P.statSync(t);o.push({type:"resource_link",uri:`file://${t}`,name:s.base,title:s.name,size:e.size}),this.logger.debug(`Added resource link: ${s.base}`)}}await this.protocol.sendPrompt({sessionId:this.sessionId,prompt:o})}async interrupt(){if(!this.connected||!this.protocol||!this.sessionId)throw new G("Not connected");await this.protocol.cancelSession({sessionId:this.sessionId}),this.logger.info("Sent interrupt signal")}async*receiveMessages(){if(!this.connected)throw new G("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=exports.ToolCallConfirmationOutcome.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: ${Q(e)}`);const t={type:exports.MessageType.ERROR,code:-1,message:String(Q(e))};this.messageQueue.push(t)}}processProtocolMessage(e){switch(e.type){case Wt.SESSION_UPDATE:{const{updateData:t}=e;let o,s;switch("agentId"in t&&t.agentId&&(o=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}}(o)),t.sessionUpdate){case z.PLAN:{const e=t.entries?.map(e=>({content:e.content||"",status:e.status||exports.PlanStatus.PENDING,priority:e.priority||exports.PlanPriority.MEDIUM}));return e&&e?.length>0?{type:exports.MessageType.PLAN,entries:e}:null}case z.TOOL_CALL:{const e={type:exports.MessageType.TOOL_CALL,id:t.toolCallId||"",label:t.title||"Tool",icon:{type:exports.ToolCallIconType.EMOJI,value:"🔧"},status:t.status||exports.ToolCallStatus.IN_PROGRESS,toolName:t.toolName,args:t.args};return o&&(e.agentId=o,e.agentInfo=s),this.pendingToolCalls.set(e.id,e),{...e}}case z.TOOL_CALL_UPDATE:{const e=t.toolCallId;let n;if(this.pendingToolCalls.has(e)?(n=this.pendingToolCalls.get(e),n.status=t.status||exports.ToolCallStatus.COMPLETED,t.toolName&&(n.toolName=t.toolName),!n.agentId&&o&&(n.agentId=o),!n.agentInfo&&s&&(n.agentInfo=s)):(n={type:exports.MessageType.TOOL_CALL,id:e,label:t.title||"Tool",icon:{type:exports.ToolCallIconType.EMOJI,value:"🔧"},status:t.status||exports.ToolCallStatus.COMPLETED,toolName:t.toolName},o&&(n.agentId=o,n.agentInfo=s),this.pendingToolCalls.set(e,n)),t.content&&t.content?.length>0){let e;const o=[];for(const s of t.content)"args"in s&&(e=s.args),"content"===s.type&&"text"===s.content?.type&&o.push(s.content.text||"");void 0!==e&&(n.args=e),o.length>0&&(n.output=o.join("\n"))}return{...n}}case z.USER_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t)return{type:exports.MessageType.USER,chunks:[{text:t}]}}return null}case z.AGENT_MESSAGE_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:exports.MessageType.ASSISTANT,chunk:{text:t}};return o&&(e.agentId=o,e.agentInfo=s),e}}return null}case z.AGENT_THOUGHT_CHUNK:{const e=t.content;if("text"===e?.type){const t=e.text||"";if(t){const e={type:exports.MessageType.ASSISTANT,chunk:{thought:t}};return o&&(e.agentId=o,e.agentInfo=s),e}}}default:return null}}case Wt.RESPONSE:return"stopReason"in(e.result||{})?{type:exports.MessageType.TASK_FINISH,stopReason:e.result.stopReason}:null;case Wt.ERROR:return{type:exports.MessageType.ERROR,code:e.code||-1,message:e.error||"Unknown error"};default:return null}}}function Qt(e){let t,o=!1,s="text";if(e.startsWith("//"))o=!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:o,messageType:s,rawData:e,jsonData:t,timestamp:Date.now()}}exports.AuthenticationError=W,exports.ConnectionError=G,exports.IFlowClient=zt,exports.IFlowError=L,exports.IFlowNotInstalledError=M,exports.IFlowProcessError=F,exports.JSONDecodeError=N,exports.PermissionError=U,exports.PortNotAvailableError=k,exports.ProtocolError=H,exports.RawDataClient=class extends zt{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: ${Q(e)}`)}}async captureRawStream(){if(this.transport)try{for await(const e of this.transport.receive()){const t=Qt("string"==typeof e?e:JSON.stringify(e));this.rawQueue.push(t),this.rawHistory.push(t);const o=this.rawQueueResolvers.shift();o&&o(t)}}catch(e){this.logger.error(`Error capturing raw stream: ${Q(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=Qt("<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}`)}},exports.TimeoutError=$,exports.TransportError=D,exports.ValidationError=j,exports.query=async function(e,t,o){const s=[],n=new zt(o);await n.connect();try{await n.sendMessage(e,t);for await(const e of n.receiveMessages())if(e.type===exports.MessageType.ASSISTANT&&e.chunk.text)s.push(e.chunk.text);else if(e.type===exports.MessageType.TASK_FINISH)break}finally{await n.disconnect()}return s.join("")},exports.queryStream=async function*(e,t,o){const s=new zt(o);await s.connect();try{await s.sendMessage(e,t);for await(const e of s.receiveMessages())if(e.type===exports.MessageType.ASSISTANT&&e.chunk.text)yield e.chunk.text;else if(e.type===exports.MessageType.TASK_FINISH)break}finally{await s.disconnect()}};
|
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 _ extends g{constructor(e,t){super(e,t),this.name="AuthenticationError"}}var O,P,C,R,$,N,L,F,M,k,G,D,U;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(O||(O={})),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"}(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"}(D||(D={})),function(e){e.PLAN="plan",e.USER="user",e.ASSISTANT="assistant",e.TOOL_CALL="tool_call",e.ERROR="error",e.TASK_FINISH="task_finish"}(U||(U={}));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=O[t]}debug(e){this.log(O.DEBUG,e)}info(e){this.log(O.INFO,e)}warn(e){this.log(O.WARN,e)}error(e,t){this.log(O.ERROR,e,t)}log(e,t,n){if(e<this.level)return;const s=`[${(new Date).toLocaleString("sv-SE").replace("T"," ")}] ${O[e]}: ${t}${n?`\n${n.stack}`:""}`;switch(e){case O.DEBUG:console.debug(s);break;case O.INFO:console.info(s);break;case O.WARN:console.warn(s);break;case O.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||P.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 _(`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 _("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===P.AUTO||this.permissionMode!==P.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,_e,Oe,Pe,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(Oe)return _e;Oe=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 _e=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)},_e}function Ge(){if(Ce)return Pe;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 Pe={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},Pe}function De(){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 Ue(){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,_t,Ot,Pt,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(Ot)return _t;Ot=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 _t={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")}},_t}function Dt(){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 Ut,jt=function(){if(Nt)return de.exports;Nt=1;const e=s,t=d,n=De(),o=Ue(),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 Pt;Ct=1;const e=(async()=>{})().constructor.prototype,t=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(e,t)]);return Pt={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)})})},Pt}(),{joinCommand:I,parseCommand:T,getEscapedCommand:x}=Dt(),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),_={isCanceled:!1};d.kill=l.bind(null,d.kill.bind(d)),d.cancel=u.bind(null,d,_);const O=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:_.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,O)};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。请使用以下命令安装:\n\n使用 npm (推荐):\n npm install -g @iflow-ai/iflow-cli@latest\n\n使用 Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\n使用 pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\n安装后,请重启终端或命令提示符。":"iFlow 需要 Node.js,但系统中未安装。\n\n请先安装 Node.js: https://nodejs.org/\n\n安装 Node.js 后,使用以下命令安装 iFlow:\n npm install -g @iflow-ai/iflow-cli@latest":'未找到 iFlow CLI。请使用以下命令安装:\n\n🍎 Mac/Linux 用户 (推荐使用安装脚本):\n bash -c "$(curl -fsSL https://cloud.iflow.cn/iflow-cli/install.sh)"\n\n或使用 npm:\n npm install -g @iflow-ai/iflow-cli@latest\n\n或使用 Yarn:\n yarn global add @iflow-ai/iflow-cli@latest\n\n或使用 pnpm:\n pnpm add -g @iflow-ai/iflow-cli@latest\n\n🐧 Ubuntu/Debian 用户可能需要:\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("父进程退出中,清理子进程");try{if(this.isWindows())try{l.execSync(`taskkill /F /T /PID ${this.process.pid}`,{encoding:"utf-8",windowsHide:!0,timeout:Wt.TASKKILL_TIMEOUT_EXIT_HANDLER})}catch(e){this.logger.debug(`taskkill 失败: ${K(e)}`)}else this.process.kill("SIGKILL")}catch(e){this.logger.debug(`清理进程时出错: ${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}`,{encoding:"utf-8",windowsHide:!0,timeout:3e3})}catch(e){this.logger.debug(`taskkill (优雅关闭) 失败: ${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}`,{encoding:"utf-8",windowsHide:!0,timeout:Wt.TASKKILL_TIMEOUT_STOP})}catch(e){this.logger.warn(`taskkill /F /T 失败,进程可能已退出或无法访问: ${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"}(Ut||(Ut={}));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:P.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:U.ERROR,code:-1,message:String(K(e))};this.messageQueue.push(t)}}processProtocolMessage(e){switch(e.type){case Ut.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:U.PLAN,entries:e}:null}case B.TOOL_CALL:{const e={type:U.TOOL_CALL,id:t.toolCallId||"",label:t.title||"Tool",icon:{type:D.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:U.TOOL_CALL,id:e,label:t.title||"Tool",icon:{type:D.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:U.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:U.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:U.ASSISTANT,chunk:{thought:t}};return n&&(e.agentId=n,e.agentInfo=s),e}}}default:return null}}case Ut.RESPONSE:return"stopReason"in(e.result||{})?{type:U.TASK_FINISH,stopReason:e.result.stopReason}:null;case Ut.ERROR:return{type:U.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===U.ASSISTANT&&e.chunk.text)s.push(e.chunk.text);else if(e.type===U.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===U.ASSISTANT&&e.chunk.text)yield e.chunk.text;else if(e.type===U.TASK_FINISH)break}finally{await s.disconnect()}}export{C as ApprovalMode,_ as AuthenticationError,T as ConnectionError,R as HookEventType,Bt as IFlowClient,g as IFlowError,S as IFlowNotInstalledError,E as IFlowProcessError,y as JSONDecodeError,O as LogLevel,U as MessageType,v as PermissionError,P 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,D 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 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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iflow-ai/iflow-cli-sdk",
|
|
3
|
-
"version": "0.1.9
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "TypeScript SDK for iFlow CLI",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -28,7 +28,8 @@
|
|
|
28
28
|
"dist",
|
|
29
29
|
"README.md",
|
|
30
30
|
"README_CN.md",
|
|
31
|
-
"LICENSE"
|
|
31
|
+
"LICENSE",
|
|
32
|
+
"CHANGELOG.md"
|
|
32
33
|
],
|
|
33
34
|
"keywords": [
|
|
34
35
|
"iflow",
|