@iflow-ai/iflow-cli-sdk 0.1.9-beta.2 → 0.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README_CN.md CHANGED
@@ -15,6 +15,7 @@
15
15
  - 🔌 **智能端口检测** - 自动查找可用端口,无冲突
16
16
  - 🔄 **双向通信** - 实时流式传输消息和响应
17
17
  - 🛠️ **工具调用管理** - 通过细粒度权限处理和控制工具执行
18
+ - 🔐 **权限请求处理** - 管理和响应工具执行权限请求
18
19
  - 🤖 **子代理支持** - 通过 `agentId` 传播跟踪和管理多个 AI 代理
19
20
  - 📋 **任务规划** - 接收和处理结构化任务计划
20
21
  - 🔍 **原始数据访问** - 调试和检查协议级消息
@@ -233,6 +234,43 @@ async function main() {
233
234
  }
234
235
  ```
235
236
 
237
+ #### 增强文件类型
238
+
239
+ SDK 支持多种文件类型,不仅仅是简单的文件路径:
240
+
241
+ ```ts
242
+ import { IFlowClient } from "@iflow-ai/iflow-cli-sdk";
243
+
244
+ const client = new IFlowClient();
245
+ await client.connect();
246
+
247
+ // 1. 使用图像数据
248
+ const image = {
249
+ type: "image" as const,
250
+ data: "base64编码的图像数据",
251
+ mimeType: "image/png"
252
+ };
253
+ await client.sendMessage("分析这个图片", [image]);
254
+
255
+ // 2. 使用文本选择
256
+ const selection = {
257
+ type: "selection" as const,
258
+ data: "const sum = (a, b) => a + b;",
259
+ uri: "file:///path/to/file.ts",
260
+ line: { start: 1, end: 2 }
261
+ };
262
+ await client.sendMessage("解释这段代码", [selection]);
263
+
264
+ // 3. 混合使用多种文件类型
265
+ await client.sendMessage("分析这些文件", [
266
+ "package.json", // 文件路径
267
+ image, // 图像数据
268
+ selection // 文本选择
269
+ ]);
270
+
271
+ await client.disconnect();
272
+ ```
273
+
236
274
  #### 高级协议特性
237
275
 
238
276
  ```ts
@@ -300,6 +338,130 @@ async function main() {
300
338
  }
301
339
  ```
302
340
 
341
+ #### 权限请求处理
342
+
343
+ 处理 AI 的工具执行权限请求:
344
+
345
+ ```ts
346
+ import { IFlowClient } from "@iflow-ai/iflow-cli-sdk";
347
+
348
+ const client = new IFlowClient();
349
+ await client.connect();
350
+ await client.sendMessage("创建文件并写入一些代码");
351
+
352
+ for await (const message of client.receiveMessages()) {
353
+ if (message.type === "permission_request") {
354
+ console.log(`工具权限请求: ${message.toolCall.title}`);
355
+ console.log(`请求ID: ${message.requestId}`);
356
+
357
+ // 显示可用选项
358
+ console.log("可用选项:");
359
+ message.options.forEach(option => {
360
+ console.log(`- ${option.optionId}`);
361
+ });
362
+
363
+ // 根据用户输入决定是批准还是取消
364
+ const userChoice = "proceed_once"; // 或者根据用户输入决定
365
+
366
+ if (userChoice === "cancel") {
367
+ await client.cancelToolConfirmation(message.requestId);
368
+ console.log("权限请求已取消");
369
+ } else {
370
+ await client.respondToToolConfirmation(message.requestId, userChoice);
371
+ console.log(`权限已批准,选项: ${userChoice}`);
372
+ }
373
+ } else if (message.type === "task_finish") {
374
+ break;
375
+ }
376
+ }
377
+
378
+ await client.disconnect();
379
+ ```
380
+
381
+ #### 配置管理
382
+
383
+ 管理会话的模型和模式配置:
384
+
385
+ ```ts
386
+ import { IFlowClient } from "@iflow-ai/iflow-cli-sdk";
387
+
388
+ const client = new IFlowClient();
389
+ await client.connect();
390
+
391
+ // 获取配置信息
392
+ const models = await client.config.get("models");
393
+ console.log("可用模型:", models);
394
+
395
+ const currentModel = await client.config.get("model");
396
+ console.log("当前模型:", currentModel);
397
+
398
+ const modes = await client.config.get("modes");
399
+ console.log("可用模式:", modes);
400
+
401
+ const currentMode = await client.config.get("mode");
402
+ console.log("当前模式:", currentMode);
403
+
404
+ // 设置配置
405
+ await client.config.set("model", "glm-4.7");
406
+ console.log("已切换到 glm-4.7 模型");
407
+
408
+ await client.config.set("mode", "plan");
409
+ console.log("已切换到 plan 模式");
410
+
411
+ await client.disconnect();
412
+ ```
413
+
414
+ #### 完整配置管理示例
415
+
416
+ ```ts
417
+ import { IFlowClient } from "@iflow-ai/iflow-cli-sdk";
418
+
419
+ async function configExample() {
420
+ const client = new IFlowClient();
421
+
422
+ try {
423
+ await client.connect();
424
+
425
+ // 获取所有可用配置
426
+ const models = await client.config.get("models");
427
+ const modes = await client.config.get("modes");
428
+ const commands = await client.config.get("commands");
429
+ const agents = await client.config.get("agents");
430
+ const skills = await client.config.get("skills");
431
+ const mcpServers = await client.config.get("mcpServers");
432
+
433
+ console.log("=== 配置信息 ===");
434
+ console.log("可用模型:", models);
435
+ console.log("可用模式:", modes);
436
+ console.log("可用命令:", commands);
437
+ console.log("可用代理:", agents);
438
+ console.log("可用技能:", skills);
439
+ console.log("可用 MCP 服务器:", mcpServers);
440
+
441
+ // 保存原始配置
442
+ const originalModel = await client.config.get("model");
443
+ const originalMode = await client.config.get("mode");
444
+
445
+ // 临时切换配置
446
+ await client.config.set("model", "glm-4.7");
447
+ await client.config.set("mode", "plan");
448
+
449
+ console.log("已切换到 glm-4.7 模型和 plan 模式");
450
+
451
+ // 恢复原始配置
452
+ await client.config.set("model", originalModel);
453
+ await client.config.set("mode", originalMode);
454
+
455
+ console.log("已恢复原始配置");
456
+
457
+ } finally {
458
+ await client.disconnect();
459
+ }
460
+ }
461
+
462
+ configExample().catch(console.error);
463
+ ```
464
+
303
465
  ## API 参考
304
466
 
305
467
  ### 核心类
@@ -308,12 +470,38 @@ async function main() {
308
470
  - **`IFlowOptions`**: 配置选项
309
471
  - **`RawDataClient`**: 访问原始协议数据
310
472
 
473
+ ### 文件类型
474
+
475
+ ```typescript
476
+ // 文件路径类型
477
+ type FilePath = string;
478
+
479
+ // 图像数据接口
480
+ interface Image {
481
+ type: "image";
482
+ data: string; // base64 编码的图像数据
483
+ mimeType: string; // 图像 MIME 类型
484
+ }
485
+
486
+ // 文本选择接口
487
+ interface Selection {
488
+ type: "selection";
489
+ data: string; // 选中的文本内容
490
+ uri: string; // 文件 URI
491
+ line: {
492
+ start: number; // 起始行号
493
+ end: number; // 结束行号
494
+ };
495
+ }
496
+ ```
497
+
311
498
  ### 消息类型
312
499
 
313
500
  - **`AssistantMessage`**: AI 助手响应,包含可选的代理信息
314
501
  - **`ToolCallMessage`**: 工具执行请求,包含执行详情(toolName, args, output)和代理信息
315
502
  - **`PlanMessage`**: 带优先级和状态的结构化任务计划
316
503
  - **`TaskFinishMessage`**: 带停止原因的任务完成信号 (end_turn, max_tokens, refusal, cancelled)
504
+ - **`PermissionRequestMessage`**: 权限请求,用于处理工具执行权限确认
317
505
 
318
506
  ### 代理信息
319
507
 
@@ -354,6 +542,8 @@ src/
354
542
  npm test
355
543
  ```
356
544
 
545
+ > 💡 **测试工具**:查看 [`mock-server/`](./mock-server/) 目录了解 ACP Mock Server,可用于无需真实 CLI 的测试和开发。
546
+
357
547
  ### 代码质量
358
548
 
359
549
  ```bash
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,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()}};
1
+ "use strict";var e=require("fs"),t=require("path"),s=require("ws"),o=require("fs/promises"),n=require("os"),i=require("net"),r=require("child_process"),a=require("assert"),l=require("events"),c=require("buffer"),d=require("stream"),u=require("util");function p(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var h,m,f,g,w,y,S,x,E,T,I,v,_,b=p(e),P=p(t),A=p(o),R=p(n),C=p(i),$=p(r);class O extends Error{constructor(e,t){super(e),this.name="IFlowError",this.details=t||{}}}class M extends O{constructor(e,t){super(e,t),this.name="TimeoutError"}}class N extends O{constructor(e,t){super(e,{rawData:t}),this.name="JSONDecodeError",this.rawData=t}}class L extends O{constructor(e,t){super(e,t),this.name="IFlowNotInstalledError"}}class k extends O{constructor(e,t){super(e,t),this.name="IFlowProcessError"}}class F extends O{constructor(e,t){super(e,t),this.name="PortNotAvailableError"}}class q extends O{constructor(e,t){super(e,t),this.name="ConnectionError"}}class U extends O{constructor(e,t){super(e,t),this.name="TransportError"}}class D extends O{constructor(e,t){super(e,t),this.name="PermissionError"}}class G extends O{constructor(e,t){super(e,t),this.name="ValidationError"}}class j extends O{constructor(e,t){super(e,t),this.name="ProtocolError"}}class H extends O{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,(m=exports.PermissionMode||(exports.PermissionMode={})).AUTO="auto",m.MANUAL="manual",m.SELECTIVE="selective",exports.ApprovalMode=void 0,(f=exports.ApprovalMode||(exports.ApprovalMode={})).DEFAULT="default",f.AUTO_EDIT="autoEdit",f.YOLO="yolo",f.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,(E=exports.ToolCallContentType||(exports.ToolCallContentType={})).DIFF="diff",E.MARKDOWN="markdown",exports.ToolCallConfirmationType=void 0,(T=exports.ToolCallConfirmationType||(exports.ToolCallConfirmationType={})).EDIT="edit",T.EXECUTE="execute",T.MCP="mcp",T.FETCH="fetch",T.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,(_=exports.MessageType||(exports.MessageType={})).PLAN="plan",_.USER="user",_.ASSISTANT="assistant",_.TOOL_CALL="tool_call",_.ERROR="error",_.TASK_FINISH="task_finish",_.ASK_USER_QUESTIONS="ask_user_questions",_.EXIT_PLAN_MODE="exit_plan_mode",_.PERMISSION_REQUEST="permission_request";const Q="2.0";var W,K,B,z;function X(e){if(e instanceof Error){const t=e,s=t.details?.data?.details;return s?`${e.message}\n${s}`:e.message}return e?String(e):"unknown error"}!function(e){e.INITIALIZE="initialize",e.AUTHENTICATE="authenticate",e.SESSION_NEW="session/new",e.SESSION_LOAD="session/load",e.SESSION_PROMPT="session/prompt",e.SESSION_CANCEL="session/cancel",e.SESSION_SET_MODE="session/set_mode",e.SESSION_SET_MODEL="session/set_model",e.SESSION_SET_THINK="session/set_think"}(W||(W={})),function(e){e.SESSION_UPDATE="session/update",e.SESSION_REQUEST_PERMISSION="session/request_permission",e.FS_READ_TEXT_FILE="fs/read_text_file",e.FS_WRITE_TEXT_FILE="fs/write_text_file",e.PUSH_TOOL_CALL="pushToolCall",e.UPDATE_TOOL_CALL="updateToolCall",e.NOTIFY_TASK_FINISH="notifyTaskFinish",e.ASK_USER_QUESTIONS="_iflow/user/questions",e.EXIT_PLAN_MODE="_iflow/plan/exit"}(K||(K={})),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={})),function(e){e.ERROR="error",e.RESPONSE="response",e.FILE_READ="file_read",e.FILE_WRITE="file_write",e.SESSION_UPDATE="session_update",e.TOOL_CALL="tool_call",e.TOOL_UPDATE="tool_update",e.TASK_FINISH="task_finish",e.ASK_USER_QUESTIONS="ask_user_questions",e.EXIT_PLAN_MODE="exit_plan_mode",e.PERMISSION_REQUEST="permission_request",e.UNKNOWN="unknown"}(z||(z={}));class J{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,s){if(e<this.level)return;const o=`[${(new Date).toLocaleString("sv-SE").replace("T"," ")}] ${exports.LogLevel[e]}: ${t}${s?`\n${s.stack}`:""}`;switch(e){case exports.LogLevel.DEBUG:console.debug(o);break;case exports.LogLevel.INFO:console.info(o);break;case exports.LogLevel.WARN:console.warn(o);break;case exports.LogLevel.ERROR:console.error(o)}}}const V=new J;function Y(e){return!!e&&"id"in e&&"result"in e&&null!=e.result}function Z(e){return!!e&&"id"in e&&"error"in e&&null!=e.error}function ee(e){return!!e&&"method"in e&&!("result"in e)&&!("error"in e)}class te{constructor(e){this.requestId=0,this.initialized=!1,this.authenticated=!1,this.pendingPermissionRequests=new Map,this.maxPendingRequests=10,this.requestTtl=300,this.logger=e.logger||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 j("Protocol not initialized. Call initialize() first.");if(!this.authenticated)throw new j("Not authenticated. Call authenticate() first.")}async sendResult(e,t){const s={jsonrpc:Q,id:e,result:t};await this.transport.send(s)}async sendError(e,t,s){const o={jsonrpc:Q,id:e,error:{code:t,message:s}};await this.transport.send(o)}async waitForReadySignal(){for await(const e of this.transport.receive()){const t=e.trim();if("//ready"===t){this.logger.info("Received //ready signal");break}t.startsWith("//")&&this.logger.debug(`Control message: ${t}`)}}async waitForMessageResponse(e,t,s){const{timeout:o,timeoutMsg:n=`Timeout after ${o} seconds`}=s||{},i=Date.now();for await(const s of this.transport.receive()){if(s.trim().startsWith("//")){this.logger.debug(`Control message: ${s.trim()}`);continue}let r;try{r=JSON.parse(s.trim())}catch(e){this.logger.error(`Failed to parse response: ${X(e)}`);continue}if(r.id===e){const e=t(r);if(void 0!==e)return e}if(o&&o>0&&Date.now()-i>o)throw new M(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(),s={jsonrpc:Q,id:t,method:W.INITIALIZE,params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}},...e}};await this.transport.send(s),this.logger.info("Sent initialize request");const o=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new j(`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(o)return o;throw new j("Connection closed during initialization")}async authenticate(e={}){const t=e.methodId||"iflow";if(this.authenticated)return void this.logger.warn("Already authenticated");const s=this.nextRequestId(),o={jsonrpc:Q,id:s,method:W.AUTHENTICATE,params:{...e,methodId:t}};await this.transport.send(o),this.logger.info(`Sent authenticate request with method: ${o.params.methodId}`);if(!await this.waitForMessageResponse(s,e=>{if("error"in e)throw new H(`Authentication failed: ${e.error?.message}`,e.error);const s=e.result||{};return s.methodId===t?(this.authenticated=!0,this.logger.info(`Authentication successful with method: ${s.methodId}`),!0):(this.authenticated=!0,this.logger.warn(`Unexpected methodId in response: ${s.methodId} (expected ${t})`),!0)},{timeout:1e4,timeoutMsg:"Authentication timeout after 10 seconds"}))throw new H("Connection closed during authentication")}async createSession(e={}){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:Q,id:t,method:W.SESSION_NEW,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(s),this.logger.info(`Sent session/new request with cwd: ${e.cwd}`);const o=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new j(`session/new failed: ${e.error?.message}`,e.error);const t=e.result||{};if(t.sessionId)return this.logger.info(`Created session: ${t.sessionId}`),t;throw new j(`Invalid session/new response: ${JSON.stringify(t)}`)},{timeout:1e4,timeoutMsg:"Session creation timeout after 10 seconds"});if(o)return o;throw new j("Connection closed while waiting for session/new response")}async loadSession(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:Q,id:t,method:W.SESSION_LOAD,params:{...e,cwd:e.cwd||process.cwd(),mcpServers:e.mcpServers||[]}};await this.transport.send(s),this.logger.info(`Sent session/load request for session: ${e.sessionId}`);if(!await this.waitForMessageResponse(t,t=>{if("error"in t){if(-32601===t.error.code)throw new j("session/load is not supported by the current iFlow version. Use session/new to create a new session instead.",t.error);throw new j(`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 j("Connection closed while waiting for session/load response")}async sendPrompt(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:Q,id:t,method:W.SESSION_PROMPT,params:e};return await this.transport.send(s),this.logger.info(`Sent prompt with ${e.prompt.length} content blocks`),t}async cancelSession(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:Q,id:t,method:W.SESSION_CANCEL,params:e};await this.transport.send(s),this.logger.info("Sent session/cancel request")}async setMode(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:Q,id:t,method:W.SESSION_SET_MODE,params:e};await this.transport.send(s),this.logger.info(`Sent session/set_mode request with modeId: ${e.modeId}`);try{const e=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new j(`session/set_mode failed: ${e.error?.message}`,e.error);return e.result},{timeout:1e4,timeoutMsg:"Set mode timeout after 10 seconds"});if(!e?.success)throw new j("session/set_mode failed: operation unsuccessful");return e.currentModeId}catch(t){throw this.logger.error(`Failed to set mode to ${e.modeId}: ${X(t)}`),t}}async setModel(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:Q,id:t,method:W.SESSION_SET_MODEL,params:e};await this.transport.send(s),this.logger.info(`Sent session/set_model request with modelId: ${e.modelId}`);try{const e=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new j(`session/set_model failed: ${e.error?.message}`,e.error);return e.result},{timeout:1e4,timeoutMsg:"Set model timeout after 10 seconds"});if(!e?.success)throw new j("session/set_model failed: operation unsuccessful");return e.currentModelId}catch(t){throw this.logger.error(`Failed to set model to ${e.modelId}: ${X(t)}`),t}}async setThink(e){this.checkAuthenticated();const t=this.nextRequestId(),s={jsonrpc:Q,id:t,method:W.SESSION_SET_THINK,params:e};await this.transport.send(s),this.logger.info(`Sent session/set_think request with thinkEnabled: ${e.thinkEnabled}, thinkConfig: ${e.thinkConfig||"default"}`);try{const e=await this.waitForMessageResponse(t,e=>{if("error"in e)throw new j(`session/set_think failed: ${e.error?.message}`,e.error);return e.result},{timeout:1e4,timeoutMsg:"Set think timeout after 10 seconds"});if(!e?.success)throw new j("session/set_think failed: operation unsuccessful");return e}catch(e){throw this.logger.error(`Failed to set think: ${X(e)}`),e}}async respondToAskUserQuestions(e,t){const s={answers:t};await this.sendResult(e,s),this.logger.info(`Sent ask_user_questions response with ${Object.keys(t).length} answers`)}async respondToExitPlanMode(e,t){const s={approved:t};await this.sendResult(e,s),this.logger.info("Sent exit_plan_mode response: "+(t?"approved":"rejected"))}async sendPermissionResponse(e,t){if(!this.pendingPermissionRequests.has(e))throw new Error(`Unknown permission request: ${e}`);const s={outcome:{outcome:"selected",optionId:t}};try{await this.sendResult(e,s),this.pendingPermissionRequests.delete(e),this.logger.info(`Sent permission response for request ${e}: ${t}`)}catch(t){throw this.logger.error(`Failed to send permission response for request ${e}: ${X(t)}`),t}}async cancelPermissionResponse(e){if(!this.pendingPermissionRequests.has(e))throw new Error(`Unknown permission request: ${e}`);const t={outcome:{outcome:"cancelled"}};try{await this.sendResult(e,t),this.pendingPermissionRequests.delete(e),this.logger.info(`Cancelled permission request: ${e}`)}catch(t){throw this.logger.error(`Failed to cancel permission request ${e}: ${X(t)}`),t}}async*handleMessages(){for await(const e of this.transport.receive()){if(e.trim().startsWith("//")){this.logger.debug(`Control message: ${e.trim()}`);continue}let t;try{t=JSON.parse(e.trim())}catch(t){throw this.logger.error(`Failed to parse message: ${X(t)}`),new N("Invalid JSON received",e)}if(ee(t)){const e=await this.handleClientMessage(t);yield e}else Y(t)?yield{type:"response",id:t.id,result:t.result}:Z(t)&&(yield{type:"error",code:t.error.code,error:`${t.error.message}, detail: ${t.error.data?.details||"unknown"}`})}}async handleClientMessage(e){const{method:t}=e;switch(t){case K.FS_READ_TEXT_FILE:return await this.handleReadTextFile(e);case K.FS_WRITE_TEXT_FILE:return await this.handleWriteTextFile(e);case K.SESSION_UPDATE:return await this.handleSessionUpdate(e);case K.SESSION_REQUEST_PERMISSION:return await this.handleRequestPermission(e);case K.PUSH_TOOL_CALL:return await this.handlePushToolCall(e);case K.UPDATE_TOOL_CALL:return await this.handleUpdateToolCall(e);case K.NOTIFY_TASK_FINISH:return await this.handleNotifyTaskFinish(e);case K.ASK_USER_QUESTIONS:return await this.handleAskUserQuestions(e);case K.EXIT_PLAN_MODE:return await this.handleExitPlanMode(e);default:return await this.handleUnknownMessage(e)}}async handleReadTextFile(e){const{id:t,method:s,params:o}=e,{path:n,limit:i,line:r}=o||{};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:s}}try{a=await this.fileHandler.readFile(n,r,i)}catch(e){const o=X(e);return this.logger.error(`Error reading file ${n}: ${o}`),void 0!==t&&await this.sendError(t,-32603,o),{type:"error",code:-32603,error:o,method:s}}return void 0!==t&&await this.sendResult(t,{content:a}),{type:"file_read",path:n,content:a}}async handleWriteTextFile(e){const{id:t,method:s,params:o}=e,{path:n,content:i}=o||{};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:s}}try{await this.fileHandler.writeFile(n,i)}catch(e){const o=X(e);return this.logger.error(`Error writing file ${n}: ${o}`),void 0!==t&&await this.sendError(t,-32603,o),{type:"error",code:-32603,error:o,method:s}}return void 0!==t&&await this.sendResult(t,{success:!0}),{type:"file_write",path:n,content:i}}async handleSessionUpdate(e){const{params:t}=e,{sessionId:s,update:o}=t;return{type:"session_update",sessionId:s,updateData:o}}async handleRequestPermission(e){const{id:t,params:s}=e,o=s.toolCall||{},n=s.options||[],i=s.sessionId;return void 0!==t?this.pendingPermissionRequests.size>=this.maxPendingRequests?(this.logger.error(`Max pending permission requests limit reached (${this.maxPendingRequests}). Rejecting new request to prevent memory leak.`),await this.sendError(t,-32e3,`Too many pending requests (${this.maxPendingRequests})`),{type:"error",code:-32e3,error:`Too many pending requests (${this.maxPendingRequests})`,method:"session/request_permission"}):(this.pendingPermissionRequests.set(t,{created_at:Date.now(),ttl:this.requestTtl,toolCall:o,options:n}),this.logger.info(`Received permission request for tool '${o.title||"unknown"}', waiting for user response (pending: ${this.pendingPermissionRequests.size}/${this.maxPendingRequests})`),{type:z.PERMISSION_REQUEST,requestId:t,sessionId:i,toolCall:o,options:n,needsUserResponse:!0}):(this.logger.error("Permission request without request_id - cannot track response"),{type:"error",code:-32600,error:"Permission request without request_id - cannot track response",method:"session/request_permission"})}async handlePushToolCall(e){const{id:t,params:s}=e,o=`tool_${this.nextRequestId()}`,n={id:o};return void 0!==t&&await this.sendResult(t,n),{type:"tool_call",id:o,params:s}}async handleUpdateToolCall(e){const{id:t,params:s}=e;return void 0!==t&&await this.sendResult(t,null),{type:"tool_update",params:s}}async handleNotifyTaskFinish(e){const{id:t,params:s}=e;return void 0!==t&&await this.sendResult(t,null),{type:"task_finish",params:s}}async handleAskUserQuestions(e){const{id:t,params:s}=e;return this.logger.info(`ask_user_questions request with ${s?.questions?.length||0} questions`),{type:"ask_user_questions",requestId:t,params:s}}async handleExitPlanMode(e){const{id:t,params:s}=e;return this.logger.info(`exit_plan_mode request with plan: ${s?.plan?.substring(0,50)}...`),{type:"exit_plan_mode",requestId:t,params:s}}async handleUnknownMessage(e){const{id:t,method:s,params:o}=e;return this.logger.warn(`Unknown method: ${s}`),void 0!==t&&await this.sendError(t,-32601,"Method not found"),{type:"unknown",method:s,params:o}}}class se{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 q("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 o=new s(this.url),n=setTimeout(()=>{o.close(),t(new M(`Connected to ${this.url} timeout after ${this.timeout/1e3}s`))},this.timeout);o.on("open",()=>{clearTimeout(n),this.connected=!0,this.logger.info(`Connected to ${this.url} succesfully`),e(o)}),o.on("error",e=>{clearTimeout(n),this.connected=!1,t(e)}),o.on("close",(e,s)=>{clearTimeout(n),this.connected=!1,t(new Error(`${s} (code: ${e})`))})})}catch(e){if(e instanceof M)throw e;throw new q(`Failed to connect to ${this.url}: ${X(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: ${X(e)}`)}this.ws=null,this.connected=!1}async send(e){this.checkConnected();try{const t="string"==typeof e?e:JSON.stringify(e);await new Promise((e,s)=>{this.ws.send(t,o=>{o?s(o):(this.logger.debug(`Sent message: ${t}`),e())})})}catch(e){throw this.connected=!1,new U(`Failed to send message: ${X(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 q&&e.details.isClosed){this.logger.info("Connection closed");break}throw new U(`Failed to receive message: ${X(e)}`)}}receiveRawData(){return new Promise((e,t)=>{if(!this.isConnected)return void t(new q("Not connected"));const s=()=>{this.ws&&(this.ws.off("close",o),this.ws.off("error",n),this.ws.off("message",i))},o=()=>{s(),this.connected=!1,t(new q("Connection closed",{isClosed:!0}))},n=e=>{s(),this.connected=!1,t(e)},i=t=>{s(),e(t.toString())};this.ws&&(this.ws.on("close",o),this.ws.on("error",n),this.ws.on("message",i))})}}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=>P.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=P.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,s){if(!this.isPathAllowed(e))throw new D(`Access denied: ${e}`);const o=P.resolve(this.cwd,e);try{if(!b.existsSync(o))throw new G(`File not found: ${e}`);try{await A.access(o,b.constants.R_OK)}catch{throw new D(`Permission denied: ${e}`)}const n=await A.stat(o);if(!n.isFile())throw new G(`Not a file: ${e}`);if(n.size>this.maxFileSize)throw new G(`File too large: ${n.size} bytes (max: ${this.maxFileSize})`);const i=await A.readFile(o,"utf-8");if(void 0!==t||void 0!==s){const o=i.split("\n"),n=t?t-1:0,r=s?n+s:o.length,a=Math.max(0,n),l=Math.min(o.length,r);return this.logger.debug(`Read ${l-a} lines from ${e}`),o.slice(a,l).join("\n")}return this.logger.debug(`Read ${i.length} bytes from ${e}`),i}catch(e){if(e instanceof G||e instanceof D)throw e;throw new G(`Failed to read file: ${X(e)}`)}}async writeFile(e,t){if(this.readOnly)throw new D("File system is in read-only mode");if(!this.isPathAllowed(e))throw new D(`Access denied: ${e}`);const s=P.resolve(this.cwd,e);try{await A.mkdir(P.dirname(s),{recursive:!0}),await A.writeFile(s,t,"utf-8"),this.logger.debug(`Wrote ${t.length} bytes to ${e}`)}catch(e){throw new G(`Failed to write file: ${X(e)}`)}}async addAllowedDir(e){const t=P.resolve(this.cwd,e);try{if(!b.existsSync(t))throw new G(`Directory does not exist: ${t}`);if(!(await A.stat(t)).isDirectory())throw new G(`Not a directory: ${t}`);this.allowedDirs.add(t),this.logger.info(`Added allowed directory: ${t}`)}catch(e){if(e instanceof G)throw e;throw new G(`Failed to add ${t} as allowed directory: ${X(e)}`)}}removeAllowedDir(e){const t=P.resolve(this.cwd,e);this.allowedDirs.delete(t),this.logger.info(`Removed allowed directory: ${t}`)}}var ne="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ie(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var re,ae,le,ce,de,ue,pe,he,me={exports:{}},fe={exports:{}};function ge(){if(ae)return re;ae=1,re=o,o.sync=function(e,o){return s(t.statSync(e),e,o)};var t=e;function s(e,t,s){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var s=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!s)return!0;if(-1!==(s=s.split(";")).indexOf(""))return!0;for(var o=0;o<s.length;o++){var n=s[o].toLowerCase();if(n&&e.substr(-n.length).toLowerCase()===n)return!0}return!1}(t,s)}function o(e,o,n){t.stat(e,function(t,i){n(t,!t&&s(i,e,o))})}return re}function we(){if(ce)return le;ce=1,le=s,s.sync=function(e,s){return o(t.statSync(e),s)};var t=e;function s(e,s,n){t.stat(e,function(e,t){n(e,!e&&o(t,s))})}function o(e,t){return e.isFile()&&function(e,t){var s=e.mode,o=e.uid,n=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),l=parseInt("010",8),c=parseInt("001",8),d=a|l;return s&c||s&l&&n===r||s&a&&o===i||s&d&&0===i}(e,t)}return le}function ye(){if(he)return pe;he=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,s=t,o=e?";":":",n=function(){if(ue)return de;var e;function t(s,o,n){if("function"==typeof o&&(n=o,o={}),!n){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,n){t(s,o||{},function(t,s){t?n(t):e(s)})})}e(s,o||{},function(e,t){e&&("EACCES"===e.code||o&&o.ignoreErrors)&&(e=null,t=!1),n(e,t)})}return ue=1,e="win32"===process.platform||ne.TESTING_WINDOWS?ge():we(),de=t,t.sync=function(t,s){try{return e.sync(t,s||{})}catch(e){if(s&&s.ignoreErrors||"EACCES"===e.code)return!1;throw e}},de}(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),r=(t,s)=>{const n=s.colon||o,i=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(s.path||process.env.PATH||"").split(n)],r=e?s.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?r.split(n):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:i,pathExt:a,pathExtExe:r}},a=(e,t,o)=>{"function"==typeof t&&(o=t,t={}),t||(t={});const{pathEnv:a,pathExt:l,pathExtExe:c}=r(e,t),d=[],u=o=>new Promise((n,r)=>{if(o===a.length)return t.all&&d.length?n(d):r(i(e));const l=a[o],c=/^".*"$/.test(l)?l.slice(1,-1):l,u=s.join(c,e),h=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;n(p(h,o,0))}),p=(e,s,o)=>new Promise((i,r)=>{if(o===l.length)return i(u(s+1));const a=l[o];n(e+a,{pathExt:c},(n,r)=>{if(!n&&r){if(!t.all)return i(e+a);d.push(e+a)}return i(p(e,s,o+1))})});return o?u(0).then(e=>o(null,e),o):u(0)};return pe=a,a.sync=(e,t)=>{t=t||{};const{pathEnv:o,pathExt:a,pathExtExe:l}=r(e,t),c=[];for(let i=0;i<o.length;i++){const r=o[i],d=/^".*"$/.test(r)?r.slice(1,-1):r,u=s.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<a.length;e++){const s=p+a[e];try{if(n.sync(s,{pathExt:l})){if(!t.all)return s;c.push(s)}}catch(e){}}}if(t.all&&c.length)return c;if(t.nothrow)return null;throw i(e)},pe}var Se,xe,Ee,Te={exports:{}};function Ie(){if(Se)return Te.exports;Se=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 ve,_e,be,Pe,Ae,Re,Ce,$e,Oe,Me,Ne,Le,ke,Fe,qe={};function Ue(){return be?_e:(be=1,_e=/^#!(.*)/)}function De(){if(Ae)return Pe;Ae=1;const e=Ue();return Pe=(t="")=>{const s=t.match(e);if(!s)return null;const[o,n]=s[0].replace(/#! ?/,"").split(" "),i=o.split("/").pop();return"env"===i?n:n?`${i} ${n}`:i},Pe}function Ge(){if(Oe)return $e;Oe=1;const s=t,o=function(){if(Ee)return xe;Ee=1;const e=t,s=ye(),o=Ie();function n(t,n){const i=t.options.env||process.env,r=process.cwd(),a=null!=t.options.cwd,l=a&&void 0!==process.chdir&&!process.chdir.disabled;if(l)try{process.chdir(t.options.cwd)}catch(e){}let c;try{c=s.sync(t.command,{path:i[o({env:i})],pathExt:n?e.delimiter:void 0})}catch(e){}finally{l&&process.chdir(r)}return c&&(c=e.resolve(a?t.options.cwd:"",c)),c}return xe=function(e){return n(e)||n(e,!0)}}(),n=function(){if(ve)return qe;ve=1;const e=/([()\][%!^"`<>&|;, *?])/g;return qe.command=function(t){return t.replace(e,"^$1")},qe.argument=function(t,s){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),s&&(t=t.replace(e,"^$1")),t},qe}(),i=function(){if(Ce)return Re;Ce=1;const t=e,s=De();return Re=function(e){const o=Buffer.alloc(150);let n;try{n=t.openSync(e,"r"),t.readSync(n,o,0,150,0),t.closeSync(n)}catch(e){}return s(o.toString())},Re}(),r="win32"===process.platform,a=/\.(?:com|exe)$/i,l=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function c(e){if(!r)return e;const t=function(e){e.file=o(e);const t=e.file&&i(e.file);return t?(e.args.unshift(e.file),e.command=t,o(e)):e.file}(e),c=!a.test(t);if(e.options.forceShell||c){const o=l.test(t);e.command=s.normalize(e.command),e.command=n.command(e.command),e.args=e.args.map(e=>n.argument(e,o));const i=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${i}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}return $e=function(e,t,s){t&&!Array.isArray(t)&&(s=t,t=null);const o={command:e,args:t=t?t.slice(0):[],options:s=Object.assign({},s),file:void 0,original:{command:e,args:t}};return s.shell?o:c(o)},$e}function je(){if(Ne)return Me;Ne=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function s(s,o){return e&&1===s&&!o.file?t(o.original,"spawn"):null}return Me={hookChildProcess:function(t,o){if(!e)return;const n=t.emit;t.emit=function(e,i){if("exit"===e){const e=s(i,o);if(e)return n.call(t,"error",e)}return n.apply(t,arguments)}},verifyENOENT:s,verifyENOENTSync:function(s,o){return e&&1===s&&!o.file?t(o.original,"spawnSync"):null},notFoundError:t},Me}function He(){if(Le)return fe.exports;Le=1;const e=r,t=Ge(),s=je();function o(o,n,i){const r=t(o,n,i),a=e.spawn(r.command,r.args,r.options);return s.hookChildProcess(a,r),a}return fe.exports=o,fe.exports.spawn=o,fe.exports.sync=function(o,n,i){const r=t(o,n,i),a=e.spawnSync(r.command,r.args,r.options);return a.error=a.error||s.verifyENOENTSync(a.status,r),a},fe.exports._parse=t,fe.exports._enoent=s,fe.exports}function Qe(){return Fe?ke:(Fe=1,ke=e=>{const t="string"==typeof e?"\n":"\n".charCodeAt(),s="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,e.length-1)),e[e.length-1]===s&&(e=e.slice(0,e.length-1)),e})}var We,Ke={exports:{}};function Be(){return We||(We=1,function(e){const s=t,o=Ie(),n=e=>{let t;e={cwd:process.cwd(),path:process.env[o()],execPath:process.execPath,...e};let n=s.resolve(e.cwd);const i=[];for(;t!==n;)i.push(s.join(n,"node_modules/.bin")),t=n,n=s.resolve(n,"..");const r=s.resolve(e.cwd,e.execPath,"..");return i.push(r),i.concat(e.path).join(s.delimiter)};e.exports=n,e.exports.default=n,e.exports.env=t=>{const s={...(t={env:process.env,...t}).env},n=o({env:s});return t.path=s[n],s[n]=e.exports(t),s}}(Ke)),Ke.exports}var ze,Xe,Je={exports:{}},Ve={exports:{}};function Ye(){if(ze)return Ve.exports;ze=1;const e=(e,t)=>{for(const s of Reflect.ownKeys(t))Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(t,s));return e};return Ve.exports=e,Ve.exports.default=e,Ve.exports}function Ze(){if(Xe)return Je.exports;Xe=1;const e=Ye(),t=new WeakMap,s=(s,o={})=>{if("function"!=typeof s)throw new TypeError("Expected a function");let n,i=0;const r=s.displayName||s.name||"<anonymous>",a=function(...e){if(t.set(a,++i),1===i)n=s.apply(this,e),s=null;else if(!0===o.throw)throw new Error(`Function \`${r}\` can only be called once`);return n};return e(a,s),t.set(a,i),a};return Je.exports=s,Je.exports.default=s,Je.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)},Je.exports}var et,tt={},st={},ot={};var nt,it,rt,at,lt,ct={};function dt(){if(nt)return ct;nt=1,Object.defineProperty(ct,"__esModule",{value:!0}),ct.SIGRTMAX=ct.getRealtimeSignals=void 0;ct.getRealtimeSignals=function(){const o=s-t+1;return Array.from({length:o},e)};const e=function(e,s){return{name:`SIGRT${s+1}`,number:t+s,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},t=34,s=64;return ct.SIGRTMAX=s,ct}function ut(){if(it)return st;it=1,Object.defineProperty(st,"__esModule",{value:!0}),st.getSignals=void 0;var e=n,t=(et||(et=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),s=dt();st.getSignals=function(){const e=(0,s.getRealtimeSignals)();return[...t.SIGNALS,...e].map(o)};const o=function({name:t,number:s,description:o,action:n,forced:i=!1,standard:r}){const{signals:{[t]:a}}=e.constants,l=void 0!==a;return{name:t,number:l?a:s,description:o,supported:l,action:n,forced:i,standard:r}};return st}function pt(){if(lt)return at;lt=1;const{signalsByName:e}=function(){if(rt)return tt;rt=1,Object.defineProperty(tt,"__esModule",{value:!0}),tt.signalsByNumber=tt.signalsByName=void 0;var e=n,t=ut(),s=dt();const o=function(e,{name:t,number:s,description:o,supported:n,action:i,forced:r,standard:a}){return{...e,[t]:{name:t,number:s,description:o,supported:n,action:i,forced:r,standard:a}}},i=(0,t.getSignals)().reduce(o,{});tt.signalsByName=i;const r=function(e,t){const s=a(e,t);if(void 0===s)return{};const{name:o,description:n,supported:i,action:r,forced:l,standard:c}=s;return{[e]:{name:o,number:e,description:n,supported:i,action:r,forced:l,standard:c}}},a=function(t,s){const o=s.find(({name:s})=>e.constants.signals[s]===t);return void 0!==o?o:s.find(e=>e.number===t)},l=function(){const e=(0,t.getSignals)(),o=s.SIGRTMAX+1,n=Array.from({length:o},(t,s)=>r(s,e));return Object.assign({},...n)}();return tt.signalsByNumber=l,tt}();return at=({stdout:t,stderr:s,all:o,error:n,signal:i,exitCode:r,command:a,escapedCommand:l,timedOut:c,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,m=(({timedOut:e,timeout:t,errorCode:s,signal:o,signalDescription:n,exitCode:i,isCanceled:r})=>e?`timed out after ${t} milliseconds`:r?"was canceled":void 0!==s?`failed with ${s}`:void 0!==o?`was killed with ${o} (${n})`:void 0!==i?`failed with exit code ${i}`:"failed")({timedOut:c,timeout:p,errorCode:n&&n.code,signal:i,signalDescription:h,exitCode:r,isCanceled:d}),f=`Command ${m}: ${a}`,g="[object Error]"===Object.prototype.toString.call(n),w=g?`${f}\n${n.message}`:f,y=[w,s,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=l,n.exitCode=r,n.signal=i,n.signalDescription=h,n.stdout=t,n.stderr=s,void 0!==o&&(n.all=o),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(c),n.isCanceled=d,n.killed=u&&!c,n},at}var ht,mt={exports:{}};function ft(){if(ht)return mt.exports;ht=1;const e=["stdin","stdout","stderr"],t=t=>{if(!t)return;const{stdio:s}=t;if(void 0===s)return e.map(e=>t[e]);if((t=>e.some(e=>void 0!==t[e]))(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${e.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof s)return s;if(!Array.isArray(s))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof s}\``);const o=Math.max(s.length,e.length);return Array.from({length:o},(e,t)=>s[t])};return mt.exports=t,mt.exports.node=e=>{const s=t(e);return"ipc"===s?"ipc":void 0===s||"string"==typeof s?[s,s,s,"ipc"]:s.includes("ipc")?s:[...s,"ipc"]},mt.exports}var gt,wt,yt,St,xt,Et,Tt={exports:{}},It={exports:{}};function vt(){return gt||(gt=1,(e=It).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")),It.exports;var e}function _t(){if(St)return yt;St=1;const e=n,t=function(){if(wt)return Tt.exports;wt=1;var e=ne.process;const t=function(e){return e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on};if(t(e)){var s,o=a,n=vt(),i=/^win/i.test(e.platform),r=l;"function"!=typeof r&&(r=r.EventEmitter),e.__signal_exit_emitter__?s=e.__signal_exit_emitter__:((s=e.__signal_exit_emitter__=new r).count=0,s.emitted={}),s.infinite||(s.setMaxListeners(1/0),s.infinite=!0),Tt.exports=function(e,n){if(!t(ne.process))return function(){};o.equal(typeof e,"function","a callback must be provided for exit handler"),!1===p&&h();var i="exit";return n&&n.alwaysLast&&(i="afterexit"),s.on(i,e),function(){s.removeListener(i,e),0===s.listeners("exit").length&&0===s.listeners("afterexit").length&&c()}};var c=function(){p&&t(ne.process)&&(p=!1,n.forEach(function(t){try{e.removeListener(t,u[t])}catch(e){}}),e.emit=g,e.reallyExit=m,s.count-=1)};Tt.exports.unload=c;var d=function(e,t,o){s.emitted[e]||(s.emitted[e]=!0,s.emit(e,t,o))},u={};n.forEach(function(o){u[o]=function(){t(ne.process)&&e.listeners(o).length===s.count&&(c(),d("exit",null,o),d("afterexit",null,o),i&&"SIGHUP"===o&&(o="SIGINT"),e.kill(e.pid,o))}}),Tt.exports.signals=function(){return n};var p=!1,h=function(){!p&&t(ne.process)&&(p=!0,s.count+=1,n=n.filter(function(t){try{return e.on(t,u[t]),!0}catch(e){return!1}}),e.emit=w,e.reallyExit=f)};Tt.exports.load=h;var m=e.reallyExit,f=function(s){t(ne.process)&&(e.exitCode=s||0,d("exit",e.exitCode,null),d("afterexit",e.exitCode,null),m.call(e,e.exitCode))},g=e.emit,w=function(s,o){if("exit"===s&&t(ne.process)){void 0!==o&&(e.exitCode=o);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}(),s=(e,t,s,n)=>{if(!o(t,s,n))return;const i=r(s),a=setTimeout(()=>{e("SIGKILL")},i);a.unref&&a.unref()},o=(e,{forceKillAfterTimeout:t},s)=>i(e)&&!1!==t&&s,i=t=>t===e.constants.signals.SIGTERM||"string"==typeof t&&"SIGTERM"===t.toUpperCase(),r=({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 yt={spawnedKill:(e,t="SIGTERM",o={})=>{const n=e(t);return s(e,t,o,n),n},spawnedCancel:(e,t)=>{e.kill()&&(t.isCanceled=!0)},setupTimeout:(e,{timeout:t,killSignal:s="SIGTERM"},o)=>{if(0===t||void 0===t)return o;let n;const i=new Promise((o,i)=>{n=setTimeout(()=>{((e,t,s)=>{e.kill(t),s(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))})(e,s,i)},t)}),r=o.finally(()=>{clearTimeout(n)});return Promise.race([i,r])},validateTimeout:({timeout:e})=>{if(void 0!==e&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},setExitHandler:async(e,{cleanup:s,detached:o},n)=>{if(!s||o)return n;const i=t(()=>{e.kill()});return n.finally(()=>{i()})}}}var bt,Pt,At,Rt,Ct,$t,Ot,Mt,Nt,Lt,kt,Ft,qt={exports:{}};function Ut(){if(Pt)return bt;Pt=1;const{PassThrough:e}=d;return bt=t=>{t={...t};const{array:s}=t;let{encoding:o}=t;const n="buffer"===o;let i=!1;s?i=!(o||n):o=o||"utf8",n&&(o=null);const r=new e({objectMode:i});o&&r.setEncoding(o);let a=0;const l=[];return r.on("data",e=>{l.push(e),i?a=l.length:a+=e.length}),r.getBufferedValue=()=>s?l:n?Buffer.concat(l,a):l.join(""),r.getBufferedLength=()=>a,r},bt}function Dt(){if(At)return qt.exports;At=1;const{constants:e}=c,t=d,{promisify:s}=u,o=Ut(),n=s(t.pipeline);class i extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function r(t,s){if(!t)throw new Error("Expected a stream");s={maxBuffer:1/0,...s};const{maxBuffer:r}=s,a=o(s);return await new Promise((s,o)=>{const l=t=>{t&&a.getBufferedLength()<=e.MAX_LENGTH&&(t.bufferedData=a.getBufferedValue()),o(t)};(async()=>{try{await n(t,a),s()}catch(e){l(e)}})(),a.on("data",()=>{a.getBufferedLength()>r&&l(new i)})}),a.getBufferedValue()}return qt.exports=r,qt.exports.buffer=(e,t)=>r(e,{...t,encoding:"buffer"}),qt.exports.array=(e,t)=>r(e,{...t,array:!0}),qt.exports.MaxBufferError=i,qt.exports}function Gt(){if(Ct)return Rt;Ct=1;const{PassThrough:e}=d;return Rt=function(){var t=[],s=new e({objectMode:!0});return s.setMaxListeners(0),s.add=o,s.isEmpty=function(){return 0==t.length},s.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(o),s;function o(e){return Array.isArray(e)?(e.forEach(o),this):(t.push(e),e.once("end",n.bind(null,e)),e.once("error",s.emit.bind(s,"error")),e.pipe(s,{end:!1}),this)}function n(e){!(t=t.filter(function(t){return t!==e})).length&&s.readable&&s.end()}},Rt}function jt(){if(Ot)return $t;Ot=1;const e=function(){if(Et)return xt;Et=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,xt=e}(),t=Dt(),s=Gt(),o=async(e,t)=>{if(e){e.destroy();try{return await t}catch(e){return e.bufferedData}}},n=(e,{encoding:s,buffer:o,maxBuffer:n})=>{if(e&&o)return s?t(e,{encoding:s,maxBuffer:n}):t.buffer(e,{maxBuffer:n})};return $t={handleInput:(t,s)=>{void 0!==s&&void 0!==t.stdin&&(e(s)?s.pipe(t.stdin):t.stdin.end(s))},makeAllStream:(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const o=s();return e.stdout&&o.add(e.stdout),e.stderr&&o.add(e.stderr),o},getSpawnedResult:async({stdout:e,stderr:t,all:s},{encoding:i,buffer:r,maxBuffer:a},l)=>{const c=n(e,{encoding:i,buffer:r,maxBuffer:a}),d=n(t,{encoding:i,buffer:r,maxBuffer:a}),u=n(s,{encoding:i,buffer:r,maxBuffer:2*a});try{return await Promise.all([l,c,d,u])}catch(n){return Promise.all([{error:n,signal:n.signal,timedOut:n.timedOut},o(e,c),o(t,d),o(s,u)])}},validateInputSync:({input:t})=>{if(e(t))throw new TypeError("The `input` option cannot be a stream in sync mode")}},$t}function Ht(){if(kt)return Lt;kt=1;const e=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],t=/^[\w.-]+$/,s=/"/g,o=/ +/g;return Lt={joinCommand:(t,s)=>e(t,s).join(" "),getEscapedCommand:(o,n)=>e(o,n).map(e=>(e=>"string"!=typeof e||t.test(e)?e:`"${e.replace(s,'\\"')}"`)(e)).join(" "),parseCommand:e=>{const t=[];for(const s of e.trim().split(o)){const e=t[t.length-1];e&&e.endsWith("\\")?t[t.length-1]=`${e.slice(0,-1)} ${s}`:t.push(s)}return t}}}var Qt=function(){if(Ft)return me.exports;Ft=1;const e=t,s=r,o=He(),n=Qe(),i=Be(),a=Ze(),l=pt(),c=ft(),{spawnedKill:d,spawnedCancel:u,setupTimeout:p,validateTimeout:h,setExitHandler:m}=_t(),{handleInput:f,getSpawnedResult:g,makeAllStream:w,validateInputSync:y}=jt(),{mergePromise:S,getSpawnedPromise:x}=function(){if(Nt)return Mt;Nt=1;const e=(async()=>{})().constructor.prototype,t=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(e,t)]);return Mt={mergePromise:(e,s)=>{for(const[o,n]of t){const t="function"==typeof s?(...e)=>Reflect.apply(n.value,s(),e):n.value.bind(s);Reflect.defineProperty(e,o,{...n,value:t})}return e},getSpawnedPromise:e=>new Promise((t,s)=>{e.on("exit",(e,s)=>{t({exitCode:e,signal:s})}),e.on("error",e=>{s(e)}),e.stdin&&e.stdin.on("error",e=>{s(e)})})},Mt}(),{joinCommand:E,parseCommand:T,getEscapedCommand:I}=Ht(),v=(t,s,n={})=>{const r=o._parse(t,s,n);return t=r.command,s=r.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=r.options).cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...n}).env=(({env:e,extendEnv:t,preferLocal:s,localDir:o,execPath:n})=>{const r=t?{...process.env,...e}:e;return s?i.env({env:r,cwd:o,execPath:n}):r})(n),n.stdio=c(n),"win32"===process.platform&&"cmd"===e.basename(t,".exe")&&s.unshift("/q"),{file:t,args:s,options:n,parsed:r}},_=(e,t,s)=>"string"==typeof t||Buffer.isBuffer(t)?e.stripFinalNewline?n(t):t:void 0===s?void 0:"",b=(e,t,o)=>{const n=v(e,t,o),i=E(e,t),r=I(e,t);let c;h(n.options);try{c=s.spawn(n.file,n.args,n.options)}catch(e){const t=new s.ChildProcess,o=Promise.reject(l({error:e,stdout:"",stderr:"",all:"",command:i,escapedCommand:r,parsed:n,timedOut:!1,isCanceled:!1,killed:!1}));return S(t,o)}const y=x(c),T=p(c,n.options,y),b=m(c,n.options,T),P={isCanceled:!1};c.kill=d.bind(null,c.kill.bind(c)),c.cancel=u.bind(null,c,P);const A=a(async()=>{const[{error:e,exitCode:t,signal:s,timedOut:o},a,d,u]=await g(c,n.options,b),p=_(n.options,a),h=_(n.options,d),m=_(n.options,u);if(e||0!==t||null!==s){const a=l({error:e,exitCode:t,signal:s,stdout:p,stderr:h,all:m,command:i,escapedCommand:r,parsed:n,timedOut:o,isCanceled:P.isCanceled,killed:c.killed});if(!n.options.reject)return a;throw a}return{command:i,escapedCommand:r,exitCode:0,stdout:p,stderr:h,all:m,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return f(c,n.options.input),c.all=w(c,n.options),S(c,A)};return me.exports=b,me.exports.sync=(e,t,o)=>{const n=v(e,t,o),i=E(e,t),r=I(e,t);let a;y(n.options);try{a=s.spawnSync(n.file,n.args,n.options)}catch(e){throw l({error:e,stdout:"",stderr:"",all:"",command:i,escapedCommand:r,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=_(n.options,a.stdout,a.error),d=_(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=l({stdout:c,stderr:d,error:a.error,signal:a.signal,exitCode:a.status,command:i,escapedCommand:r,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:i,escapedCommand:r,exitCode:0,stdout:c,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},me.exports.command=(e,t)=>{const[s,...o]=T(e);return b(s,o,t)},me.exports.commandSync=(e,t)=>{const[s,...o]=T(e);return b.sync(s,o,t)},me.exports.node=(e,t,s={})=>{t&&!Array.isArray(t)&&"object"==typeof t&&(s=t,t=[]);const o=c.node(s),n=process.execArgv.filter(e=>!e.startsWith("--inspect")),{nodePath:i=process.execPath,nodeOptions:r=n}=s;return b(i,[...r,e,...Array.isArray(t)?t:[]],{...s,stdin:void 0,stdout:void 0,stderr:void 0,stdio:o,shell:!1})},me.exports}(),Wt=ie(Qt);class Kt{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,this.stream=e.stream||!1}get url(){if(!this.port)throw new k("iFlow process not started");return`ws://localhost:${this.port}/acp`}isRunning(){return!!this.process&&!this.process.killed&&null===this.process.exitCode}isWindows(){return"win32"===R.platform()}which(e){try{const t=this.isWindows()?"where":"which",s=$.execSync(`${t} ${e}`,{encoding:"utf-8",windowsHide:!0});return s.trim().split("\n")[0].trim()||null}catch{return null}}fileExists(e){try{return b.existsSync(e)&&b.statSync(e).isFile()}catch{return!1}}getFallbackLocations(){const e=R.homedir(),t=R.platform();if(this.isWindows())return[P.join(e,"AppData","Roaming","npm","iflow.cmd"),P.join(e,"AppData","Local","npm","iflow.cmd"),P.join(e,"AppData","Roaming","npm","iflow.exe"),P.join("C:","Program Files","nodejs","iflow.cmd"),P.join("C:","Program Files (x86)","nodejs","iflow.cmd"),P.join(e,".npm-global","iflow.cmd"),P.join(e,"node_modules",".bin","iflow.cmd")];{const s=["/usr/local/bin/iflow",P.join(e,".npm-global","bin","iflow"),P.join(e,".local","bin","iflow"),P.join(e,"node_modules",".bin","iflow"),P.join(e,".yarn","bin","iflow"),P.join(e,".config","yarn","global","node_modules",".bin","iflow"),P.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 s=null!==this.which("npm"),o=null!==this.which("node");let n;throw n=this.isWindows()?s||o?"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 L(n)}isPortAvailable(e,t=1e3){return new Promise(s=>{const o=C.createServer(),n=setTimeout(()=>{o.close(),s(!1)},t);o.listen(e,"localhost",()=>{clearTimeout(n),o.once("close",()=>{s(!0)}),o.close()}),o.once("error",()=>{clearTimeout(n),s(!1)})})}async findAvailablePort(){for(let e=0;e<10;e++){const t=this.startPort+e;if(await this.isPortAvailable(t))return this.logger.debug(`Found available port: ${t}`),t}throw new F(`No available port found in range ${this.startPort}-${this.startPort+10-1}. Please specify a different port range or free up some ports.`)}async start(){if(this.isRunning())return this.url;this.iflowPath=this.findIflowPath(),this.port=await this.findAvailablePort();const e=[this.iflowPath,"--experimental-acp","--port",this.port.toString()];this.stream&&e.push("--stream"),this.logger.info(`Starting iFlow process: ${e.join(" ")}`);try{if(this.process=Wt(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 k(`Failed to start iFlow process: ${X(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{$.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:Kt.TASKKILL_TIMEOUT_EXIT_HANDLER,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill failed: ${X(e)}`)}else this.process.kill("SIGKILL")}catch(e){this.logger.debug(`Error during process cleanup: ${X(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{$.execSync(`taskkill /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:3e3,stdio:"ignore"})}catch(e){this.logger.debug(`taskkill (graceful shutdown) failed: ${X(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{$.execSync(`taskkill /F /T /PID ${this.process.pid}`,{windowsHide:!0,timeout:Kt.TASKKILL_TIMEOUT_STOP,stdio:"ignore"})}catch(e){this.logger.warn(`taskkill /F /T failed, process may have already exited or is inaccessible: ${X(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: ${X(e)}`)}finally{this.port=null,this.process=null}}}async onSpawn(e=5e3){return new Promise((t,s)=>{if(!this.process)return void s(new Error("Process not initialized"));const o=setTimeout(()=>{s(new Error(`Process spawn timeout after ${e}ms`))},e);this.process.once("spawn",()=>{clearTimeout(o),setTimeout(t,2e3)})})}}Kt.TASKKILL_TIMEOUT_EXIT_HANDLER=3e3,Kt.TASKKILL_TIMEOUT_STOP=5e3;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.pendingAskUserQuestionsRequestId=null,this.pendingQuestions=[],this.pendingExitPlanModeRequestId=null,this.pendingPermissionRequests=new Map,this.url=null,this.sessionId=null,this.processManager=null,this.processStarted=!1,this.modes=null,this.models=null,this.availableCommands=[],this.availableAgents=[],this.availableSkills=[],this.availableMcpServers=[],this.config={get:async e=>{switch(e){case"models":return this.models?.availableModels||[];case"model":return this.models?.currentModelId||null;case"modes":return this.modes?.availableModes||[];case"mode":return this.modes?.currentModeId||null;case"commands":return this.availableCommands;case"agents":return this.availableAgents;case"skills":return this.availableSkills;case"mcpServers":return this.availableMcpServers;default:throw new Error(`Unknown config key: ${e}`)}},set:async(e,t)=>{if(!this.connected||!this.protocol||!this.sessionId)throw new q("Not connected. Call connect() first.");switch(e){case"model":{const e=t;try{const t=await this.protocol.setModel({sessionId:this.sessionId,modelId:e});if(!t||!this.models){throw new Error(t?"Models not available":"No result returned from server")}this.models.currentModelId=t,this.logger.info(`Set model to: ${t}`)}catch(t){throw this.logger.error(`Failed to set model to ${e}: ${X(t)}`),t}break}case"mode":{const e=t;try{const t=await this.protocol.setMode({sessionId:this.sessionId,modeId:e});if(!t||!this.modes){throw new Error(t?"Modes not available":"No result returned from server")}this.modes.currentModeId=t,this.logger.info(`Set mode to: ${t}`)}catch(t){throw this.logger.error(`Failed to set mode to ${e}: ${X(t)}`),t}break}default:throw new Error(`Cannot set config key: ${e}. Only 'model' and 'mode' are supported.`)}}},this.options={url:"ws://localhost:8090/acp",cwd:process.cwd(),timeout:3e4,logLevel:"INFO",fileMaxSize:10485760,permissionMode:exports.PermissionMode.AUTO,authMethodId:"iflow",autoStartProcess:!0,processStartPort:8090,...e},this.logger=new J({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 se({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 Kt({logger:this.logger,startPort:this.options.processStartPort,stream:this.options.stream});try{const e=await this.processManager.start();this.url=e,this.processStarted=!0,this.logger.info(`Started iFlow process at ${e}`),await new Promise(e=>setTimeout(e,1e3))}catch(e){throw e instanceof L?(this.logger.error("iFlow not installed"),L):(this.logger.error(`Failed to start iFlow process: ${X(e)}`),new q(`Failed to start iFlow process: ${X(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 se({url:this.options.url,logger:this.logger,timeout:this.options.timeout}),this.protocol=new te({logger:this.logger,transport:this.transport,fileHandler:e,permissionMode:this.options.permissionMode,autoApproveTypes:this.options.autoApproveTypes}),await this.transport.connect();const t=await this.protocol.initialize({mcpServers:this.options.mcpServers,hooks:this.options.hooks,commands:this.options.commands,agents:this.options.agents});let s;this.authenticated=t.isAuthenticated||!1,this.authenticated||(await this.protocol.authenticate({methodId:this.options.authMethodId,methodInfo:this.options.authMethodInfo}),this.authenticated=!0),this.options.sessionId&&(s=await this.protocol.loadSession({sessionId:this.options.sessionId,mcpServers:this.options.mcpServers})),s=await this.protocol.createSession({cwd:this.options.cwd||process.cwd(),mcpServers:this.options.mcpServers,hooks:this.options.hooks,commands:this.options.commands,agents:this.options.agents,settings:this.options.sessionSettings}),this.sessionId=s.sessionId,s.modes&&(this.modes=s.modes),s._meta?.models&&(this.models=s._meta.models),s._meta?.availableCommands&&(this.availableCommands=s._meta.availableCommands),s._meta?.availableAgents&&(this.availableAgents=s._meta.availableAgents),s._meta?.availableSkills&&(this.availableSkills=s._meta.availableSkills),s._meta?.availableMcpServers&&(this.availableMcpServers=s._meta.availableMcpServers),this.connected=!0,this.messageTask=this.handleMessages(),this.logger.info("Connected to iFlow")}catch(e){throw await this.disconnect(),new q(`Failed to connect: ${X(e)}`)}}async loadSession(e){if(!this.connected||!this.protocol)throw new q("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 q("Not connected. Call connect() first.");const s=[{type:"text",text:e}];if(t?.length)for(const e of t)if("object"!=typeof e||"image"!==e.type){if("object"==typeof e&&"selection"===e.type){const t={activeFile:{path:e.uri,cursor:{line:e.line?.start||0,character:0},selectedText:e.data}},o=`Here is the user's editor context as a JSON object. This is for your information only.\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``;s.push({type:"text",text:o}),this.logger.debug("Added selection context");continue}if("string"==typeof e){const t=P.resolve(this.options.cwd||process.cwd(),e),o=P.parse(e);if(!b.existsSync(t)){this.logger.warn(`File not found, skipping: ${t}`);continue}const n=o.ext.toLowerCase();if([".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg"].includes(n))try{const e=b.readFileSync(t).toString("base64"),i={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".bmp":"image/bmp",".webp":"image/webp",".svg":"image/svg+xml"};s.push({type:"image",data:e,mimeType:i[n]||"image/unknown"}),this.logger.debug(`Added image file: ${o.base}`)}catch(e){this.logger.error(`Failed to read image file ${t}: ${X(e)}`);continue}else if([".mp3",".wav",".m4a",".ogg",".flac"].includes(n))try{const e=b.readFileSync(t).toString("base64"),i={".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".flac":"audio/flac"};s.push({type:"audio",data:e,mimeType:i[n]||"audio/unknown"}),this.logger.debug(`Added audio file: ${o.base}`)}catch(e){this.logger.error(`Failed to read audio file ${t}: ${X(e)}`);continue}else{const e=b.statSync(t);s.push({type:"resource_link",uri:`file://${t}`,name:o.base,title:o.name,size:e.size}),this.logger.debug(`Added resource link: ${o.base}`)}}}else s.push({type:"image",data:e.data,mimeType:e.mimeType}),this.logger.debug("Added image data");await this.protocol.sendPrompt({sessionId:this.sessionId,prompt:s})}async interrupt(){if(!this.connected||!this.protocol||!this.sessionId)throw new q("Not connected");await this.protocol.cancelSession({sessionId:this.sessionId}),this.logger.info("Sent interrupt signal")}async*receiveMessages(){if(!this.connected)throw new q("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 respondToAskUserQuestions(e){if(!this.connected||!this.protocol)throw new q("Not connected");if(null===this.pendingAskUserQuestionsRequestId)throw new Error("No pending ask_user_questions request");for(const t of this.pendingQuestions){const s=e[t.header];if(void 0===s)throw new G(`Missing answer for question: ${t.header}`);if(t.multiSelect){if(!Array.isArray(s))throw new G(`Question "${t.header}" requires multiple selections (array)`);const e=t.options?.map(e=>e.label)||[];for(const o of s)if(!e.includes(o))throw new G(`Invalid option "${o}" for question "${t.header}"`)}else{if(Array.isArray(s))throw new G(`Question "${t.header}" requires single selection (string)`);if(!t.options.map(e=>e.label).includes(s))throw new G(`Invalid option "${s}" for question "${t.header}"`)}}await this.protocol.respondToAskUserQuestions(this.pendingAskUserQuestionsRequestId,e),this.pendingAskUserQuestionsRequestId=null,this.pendingQuestions=[],this.logger.info("Sent ask_user_questions response")}async respondToExitPlanMode(e){if(!this.connected||!this.protocol)throw new q("Not connected");if(null===this.pendingExitPlanModeRequestId)throw new Error("No pending exit_plan_mode request");await this.protocol.respondToExitPlanMode(this.pendingExitPlanModeRequestId,e),this.pendingExitPlanModeRequestId=null,this.logger.info("Sent exit_plan_mode response: "+(e?"approved":"rejected"))}async respondToToolConfirmation(e,t){if(!this.connected||!this.protocol)throw new q("Not connected");if(!this.pendingPermissionRequests.has(e))throw new Error(`No pending permission request with ID: ${e}`);await this.protocol.sendPermissionResponse(e,t),this.pendingPermissionRequests.delete(e),this.logger.info(`Sent tool confirmation response for request ${e}: ${t}`)}async cancelToolConfirmation(e){if(!this.connected||!this.protocol)throw new q("Not connected");if(!this.pendingPermissionRequests.has(e))throw new Error(`No pending permission request with ID: ${e}`);await this.protocol.cancelPermissionResponse(e),this.pendingPermissionRequests.delete(e),this.logger.info(`Cancelled tool confirmation request: ${e}`)}async setThink(e){if(!this.connected||!this.protocol||!this.sessionId)throw new q("Not connected. Call connect() first.");try{const t=await this.protocol.setThink({sessionId:this.sessionId,thinkEnabled:e.enabled,thinkConfig:e.config});return this.logger.info(`Set think mode: enabled=${t.currentThinkEnabled}, config=${t.currentThinkConfig||"default"}`),t}catch(e){throw this.logger.error(`Failed to set think mode: ${X(e)}`),e}}async handleMessages(){if(this.protocol)try{for await(const e of this.protocol.handleMessages()){const t=this.processProtocolMessage(e);t&&this.messageQueue.push(t)}}catch(e){this.logger.error(`Error in message handler: ${X(e)}`);const t={type:exports.MessageType.ERROR,code:-1,message:String(X(e))};this.messageQueue.push(t)}}processProtocolMessage(e){switch(e.type){case z.SESSION_UPDATE:{const{updateData:t}=e;let s,o;switch("agentId"in t&&t.agentId&&(s=t.agentId,o=function(e){const t=e.split("-");return"subagent"!==t[0]||t.length<4?{agentId:e}:4===t.length?{agentId:e,taskId:["null","undefined"].includes(t[1])?void 0:t[1],agentIndex:parseInt(t[2])||void 0,timestamp:parseInt(t[3])||void 0}:{agentId:e,taskId:t.slice(1,-2).join("-"),agentIndex:parseInt(t[t.length-2])||void 0,timestamp:parseInt(t[t.length-1])||void 0}}(s)),t.sessionUpdate){case B.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 B.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 s&&(e.agentId=s,e.agentInfo=o),this.pendingToolCalls.set(e.id,e),{...e}}case B.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&&s&&(n.agentId=s),!n.agentInfo&&o&&(n.agentInfo=o)):(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},s&&(n.agentId=s,n.agentInfo=o),this.pendingToolCalls.set(e,n)),t.content&&t.content?.length>0){let e;const s=[];for(const o of t.content)"args"in o&&(e=o.args),"content"===o.type&&"text"===o.content?.type&&s.push(o.content.text||"");void 0!==e&&(n.args=e),s.length>0&&(n.output=s.join("\n"))}return{...n}}case B.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 B.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 s&&(e.agentId=s,e.agentInfo=o),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:exports.MessageType.ASSISTANT,chunk:{thought:t}};return s&&(e.agentId=s,e.agentInfo=o),e}}}default:return null}}case z.RESPONSE:{const t=e.result;return t&&"object"==typeof t&&"stopReason"in t?{type:exports.MessageType.TASK_FINISH,stopReason:t.stopReason}:null}case z.ERROR:return{type:exports.MessageType.ERROR,code:e.code||-1,message:e.error||"Unknown error"};case z.ASK_USER_QUESTIONS:{const t=e,{questions:s}=t.params||{};return null!==this.pendingAskUserQuestionsRequestId?(this.logger.warn("Another ask_user_questions request is already pending, ignoring new request"),null):(this.pendingAskUserQuestionsRequestId=t.requestId,this.pendingQuestions=s||[],{type:exports.MessageType.ASK_USER_QUESTIONS,questions:s||[]})}case z.EXIT_PLAN_MODE:{const t=e,{plan:s}=t.params||{};return null!==this.pendingExitPlanModeRequestId?(this.logger.warn("Another exit_plan_mode request is already pending, ignoring new request"),null):(this.pendingExitPlanModeRequestId=t.requestId,{type:exports.MessageType.EXIT_PLAN_MODE,plan:s||""})}case"permission_request":{const t=e,{requestId:s,sessionId:o,toolCall:n,options:i}=t;return this.pendingPermissionRequests.has(s)?(this.logger.warn(`Permission request ${s} is already pending, ignoring new request`),null):(this.pendingPermissionRequests.set(s,{toolCall:n,options:i,sessionId:o}),{type:exports.MessageType.PERMISSION_REQUEST,requestId:s,sessionId:o,toolCall:n,options:i})}default:return null}}}function zt(e){let t,s=!1,o="text";if(e.startsWith("//"))s=!0,o="control";else try{t=JSON.parse(e),t&&"method"in t?o=`method:${t.method}`:t&&("result"in t||"error"in t)?o="response":t&&"type"in t&&(o=t.type)}catch{}return{isControl:s,messageType:o,rawData:e,jsonData:t,timestamp:Date.now()}}exports.AuthenticationError=H,exports.ConnectionError=q,exports.IFlowClient=Bt,exports.IFlowError=O,exports.IFlowNotInstalledError=L,exports.IFlowProcessError=k,exports.JSONDecodeError=N,exports.PermissionError=D,exports.PortNotAvailableError=F,exports.ProtocolError=j,exports.RawDataClient=class 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: ${X(e)}`)}}async captureRawStream(){if(this.transport)try{for await(const e of this.transport.receive()){const t=zt("string"==typeof e?e:JSON.stringify(e));this.rawQueue.push(t),this.rawHistory.push(t);const s=this.rawQueueResolvers.shift();s&&s(t)}}catch(e){this.logger.error(`Error capturing raw stream: ${X(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=zt("<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=M,exports.TransportError=U,exports.ValidationError=G,exports.query=async function(e,t,s){const o=[],n=new Bt(s);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)o.push(e.chunk.text);else if(e.type===exports.MessageType.TASK_FINISH)break}finally{await n.disconnect()}return o.join("")},exports.queryStream=async function*(e,t,s){const o=new Bt(s);await o.connect();try{await o.sendMessage(e,t);for await(const e of o.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 o.disconnect()}};