๐Ÿš€ DAY 5 OF LAUNCH WEEK: Introducing Socket Firewall Enterprise.Learn more โ†’
Socket
Book a DemoInstallSign in
Socket

@iflow-ai/iflow-cli-sdk

Package Overview
Dependencies
Maintainers
5
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@iflow-ai/iflow-cli-sdk

TypeScript SDK for iFlow CLI

latest
Source
npmnpm
Version
0.1.2
Version published
Maintainers
5
Created
Source

iFlow CLI TypeScript SDK

License WebSocket Protocol

English | ไธญๆ–‡

A powerful TypeScript SDK for interacting with iFlow CLI using the Agent Communication Protocol (ACP). Build AI-powered applications with full control over conversations, tool execution, and SubAgent orchestration.

โœจ Key Feature: The SDK automatically manages the iFlow process - no manual setup required!

Features

  • ๐Ÿš€ Automatic Process Management - Zero-config setup! SDK auto-starts and manages iFlow CLI
  • ๐Ÿ”Œ Smart Port Detection - Automatically finds available ports, no conflicts
  • ๐Ÿ”„ Bidirectional Communication - Real-time streaming of messages and responses
  • ๐Ÿ› ๏ธ Tool Call Management - Handle and control tool executions with fine-grained permissions
  • ๐Ÿค– SubAgent Support - Track and manage multiple AI agents with agentId propagation
  • ๐Ÿ“‹ Task Planning - Receive and process structured task plans
  • ๐Ÿ” Raw Data Access - Debug and inspect protocol-level messages
  • โšก Async/Await Support - Modern asynchronous Python with full type hints
  • ๐ŸŽฏ Simple & Advanced APIs - From one-line queries to complex conversation management
  • ๐Ÿ“ฆ Full ACP v1 Protocol - Complete implementation of the Agent Communication Protocol
  • ๐Ÿšฆ Advanced Approval Modes - Including default, autoEdit, yolo, and plan modes
  • ๐Ÿ”— MCP Server Integration - Support for Model Context Protocol servers
  • ๐Ÿช Lifecycle Hooks - Execute commands at different stages of conversation
  • ๐ŸŽฎ Session Settings - Fine-grained control over model behavior and tools
  • ๐Ÿค– Custom Agents - Define specialized agents with custom prompts and tools

Installation

1. Install iFlow CLI

If you haven't installed iFlow CLI yet:

Mac/Linux/Ubuntu:

bash -c "$(curl -fsSL https://cloud.iflow.cn/iflow-cli/install.sh)"

Windows:

npm install -g @iflow-ai/iflow-cli@latest

2. Install the SDK

Install from NPM:

npm install --save @iflow-ai/iflow-cli-sdk

Quick Start

The SDK automatically manages the iFlow process - no manual setup required!

Default Usage (Automatic Process Management)

import { IFlowClient } from "@iflow-ai/iflow-cli-sdk";

async function main() {
  // SDK automatically:
  // 1. Detects if iFlow is installed
  // 2. Starts iFlow process if not running
  // 3. Finds an available port
  // 4. Cleans up on exit
  const client = new IFlowClient();

  await client.connect();
  await client.sendMessage("Hello, iFlow!");

  for await (const message in client.receiveMessages()) {
    console.log(message);
    // Process messages...
  }
}

No need to manually start iFlow! The SDK handles everything for you.

Advanced: Manual Process Control

If you need to manage iFlow yourself (rare cases):

import { IFlowClient } from "@iflow-ai/iflow-cli-sdk";

async function main() {
  // Disable automatic process management
  const client = new IFlowClient({
    url: "ws://localhost:8090/acp", // Connect to existing iFlow
    autoStartProcess: false,
  });

  await client.connect();
  await client.sendMessage("Hello, iFlow!");
}

Note: Manual mode requires you to start iFlow separately:

iflow --experimental-acp --port 8090

Simple Examples

Simple Query

import { query } from "@iflow-ai/iflow-cli-sdk";

async function main() {
  const response = await query("What is the capital of France?");
  console.log(response); // "The capital of France is Paris."
}

Interactive Conversation

import { IFlowClient, MessageType } from "@iflow-ai/iflow-cli-sdk";

async function main() {
  const client = new IFlowClient();

  await client.connect();
  await client.sendMessage("Explain quantum computing");

  for await (const message in client.receiveMessages()) {
    if (message.type === MessageType.ASSISTANT && message.chunk.text) {
      console.log(message.chunk.text);
    } else if (message.type === MessageType.TASK_FINISH) {
      break;
    }
  }
}

Tool Call Control with Agent Information

import { IFlowClient, PermissionMode, MessageType } from "@iflow-ai/iflow-cli-sdk";

async function main() {
  const client = new IFlowClient({
    permissionMode: PermissionMode.AUTO,
  })

  await client.connect();
  await client.sendMessage("Create a file called test.txt");

  for await (const message in client.receiveMessages()) {
    if (message.type === MessageType.TOOL_CALL) {
      console.log(`Tool name: ${message.toolName}`);
      console.log(`Tool status: ${message.status}`);

      if (message.agentInfo) {
        console.log(`Agent ID: ${message.agentInfo.agentId}`);
        console.log(`Task ID: ${message.agentInfo.taskId}`);
        console.log(`Agent index: ${message.agentInfo.agentIndex}`);
      }

      if (message.args) {
        console.log(message.args);
      }
      if (message.output) {
        console.log(message.output);
      }
    } else if (message.type === MessageType.TASK_FINISH) {
      break;
    }
  }
}

Working with AgentInfo

import { IFlowClient, MessageType } from "@iflow-ai/iflow-cli-sdk";

const options: IFlowOptions = {
  agents: [
    {
      agentType: "code-reviewer",
      name: "reviewer",
      description: "Code review specialist",
      whenToUse: "For code review and quality checks",
      allowedTools: ["fs", "grep"],
      allowedMcps: ["eslint", "prettier"],
      systemPrompt: "You are a code review expert.",
      proactive: False,
      location: "project",
    },
    {
      agentType: "test-writer",
      name: "tester",
      description: "Test writing specialist",
      whenToUse: "For writing unit and integration tests",
      allowedTools: ["fs", "bash"],
      systemPrompt: "You are a test writing expert.",
      location: "project",
    },
  ],
};

async function main() {
  const client = new IFlowClient(options)

  await client.connect();
  await client.sendMessage("$test-writer Write a unit test");

  for await (const message in client.receiveMessages()) {
    if (message.type === MessageType.TOOL_CALL) {
      console.log(`Tool name: ${message.toolName}`);

      if (message.args) {
        console.log(message.args);
      }
      if (message.output) {
        console.log(message.output);
      }
    } if (message.type === MessageType.ASSISTANT && message.chunk.text) {
      console.log(message.chunk.text);
    } else if (message.type === MessageType.TASK_FINISH) {
      break;
    }
  }
}

Advanced Protocol Features

import { IFlowClient, IFlowOptions, ApprovalMode, HookEventType } from "@iflow-ai/iflow-cli-sdk";

const options: IFlowOptions = {
  mcpServers: [
    {
      name: "filesystem",
      command: "mcp-server-filesystem",
      args: ["--allowed-dirs", "/workspace"],
      env: [
        {
          name: "DEBUG",
          value: "1",
        },
      ],
    },
  ],

  sessionSettings: {
    allowed_tools: ["read_file", "write_file", "execute_code"],
    system_prompt: "You are an expert Python developer",
    permission_mode: ApprovalMode.AUTO_EDIT,
    max_turns: 100,
  },

  hooks: {
    [HookEventType.PRE_TOOL_USE]: [
      {
        hooks: {
          command: "echo 'Processing request...'",
          timeout: 5,
        },
      },
    ],
  },

  commands: [
    {
      name: "test",
      content: "pytest --verbose",
    },
  ],

  agents: [
    {
      agentType: "python-expert",
      whenToUse: "For Python development tasks",
      allowedTools: ["edit_file", "run_python", "debug"],
      systemPrompt: "You are a Python expert focused on clean, efficient code",
      name: "Python Expert",
      description: "Specialized in Python development",
    },
  ],
};

async function main() {
  const client = new IFlowClient(options);

  await client.connect();
  await client.sendMessage("$test-writer Write a unit test");

  // Process responses...
}

API Reference

Core Classes

  • IFlowClient: Main client for bidirectional communication
  • IFlowOptions: Configuration options
  • RawDataClient: Access to raw protocol data

Message Types

  • AssistantMessage: AI assistant responses with optional agent information
  • ToolCallMessage: Tool execution requests with execution details (toolName, args, output) and agent information
  • PlanMessage: Structured task plans with priority and status
  • TaskFinishMessage: Task completion signal with stop reason (end_urn, max_tokens, refusal, cancelled)

Agent Information

  • AgentInfo: Agent metadata extracted from iFlow's agentId format (agentId, taskId, agentIndex, timestamp)

Convenience Functions

  • query(prompt): Simple synchronous query
  • queryStream(prompt): Streaming responses

Project Structure

src/
โ”œโ”€โ”€ internals/
โ”‚   โ”œโ”€โ”€ FileHandler.ts        # File access
โ”‚   โ”œโ”€โ”€ ProcessManager.ts     # iFlow process management
โ”‚   โ”œโ”€โ”€ Protocol.ts           # ACP protocol handler
โ”‚   โ””โ”€โ”€ Transport.ts          # WebSocket transport layer
โ”œโ”€โ”€ types/
โ”‚   โ”œโ”€โ”€ acp.ts                # ACP data types
โ”‚   โ”œโ”€โ”€ messages.ts           # Message types
โ”‚   โ””โ”€โ”€ options.ts            # iFlow options
โ”œโ”€โ”€ utils/
โ”‚   โ”œโ”€โ”€ logger.ts             # Logs util
โ”‚   โ””โ”€โ”€ parseAgentId.ts       # Parse agent id
โ”œโ”€โ”€ IFlowClient.ts            # Main IFlowClient implementation
โ”œโ”€โ”€ RawDataClient.ts          # Raw protocol access
โ”œโ”€โ”€ query.ts                  # Simple query functions
โ””โ”€โ”€ index.ts                  # Main entry

Development

Running Tests

npm test

Code Quality

# Lint code
npm run lint

# Format code
npm run format

Protocol Support

The SDK implements the Agent Communication Protocol (ACP) v1 with full extension support, including:

  • Session Management: Create, load, and manage conversation sessions with advanced settings
  • Message Types:
    • agent_message_chunk - Assistant responses
    • agent_thought_chunk - Internal reasoning
    • tool_call / tool_call_update - Tool execution lifecycle
    • plan - Structured task planning with priorities
    • user_message_chunk - User message echoing
    • stop_reason - Task completion with reason (end_turn, max_tokens, refusal, cancelled)
  • Authentication: Built-in iFlow authentication with token support
  • File System Access: Read/write file permissions with configurable limits
  • SubAgent Support: Full agentId tracking and management
  • Advanced Features:
    • MCP Servers: Integrate Model Context Protocol servers for extended capabilities
    • Approval Modes: DEFAULT, AUTO_EDIT, YOLO (auto-approve all), PLAN modes
    • Session Settings: Control allowed tools, system prompts, model selection
    • Lifecycle Hooks: Execute commands at different conversation stages
    • Custom Commands: Define and execute custom commands
    • Specialized Agents: Create agents with specific expertise and tool access

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Built with โค๏ธ for the AI development community

Keywords

iflow

FAQs

Package last updated on 21 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts