iflow-cli-sdk


Nameiflow-cli-sdk JSON
Version 0.1.8 PyPI version JSON
download
home_pagehttps://github.com/yourusername/iflow-cli-sdk-python
SummaryPython SDK for iFlow CLI - AI Agent Integration
upload_time2025-10-27 07:32:38
maintainerNone
docs_urlNone
authoriFlow Team
requires_python>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # iFlow Python SDK

[![PyPI Version](https://img.shields.io/pypi/v/iflow-cli-sdk)](https://pypi.org/project/iflow-cli-sdk/)
[![Python Version](https://img.shields.io/badge/python-3.8%2B-blue)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
[![WebSocket Protocol](https://img.shields.io/badge/protocol-ACP%20v1-orange)](docs/protocol.md)

[English](README.md) | [ไธญๆ–‡](README_CN.md)

A powerful Python 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 `agent_id` 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, AUTO_EDIT, 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
bash -c "$(curl -fsSL https://gitee.com/iflow-ai/iflow-cli/raw/main/install.sh)"
```

**Windows:**
```bash
npm install -g @iflow-ai/iflow-cli@latest
```

### 2. Install the SDK

**Install from PyPI (Recommended):**

```bash
pip install iflow-cli-sdk
```

**Or install from source:**

```bash
git clone https://github.com/yourusername/iflow-cli-sdk-python.git
cd iflow-cli-sdk-python
pip install -e .
```

## Quick Start

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

### Default Usage (Automatic Process Management)

```python
import asyncio
from iflow_sdk import IFlowClient

async def 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
    async with IFlowClient() as client:
        await client.send_message("Hello, iFlow!")
        
        async for message in client.receive_messages():
            print(message)
            # Process messages...

asyncio.run(main())
```

**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):

```python
import asyncio
from iflow_sdk import IFlowClient, IFlowOptions

async def main():
    # Disable automatic process management
    options = IFlowOptions(
        auto_start_process=False,
        url="ws://localhost:8090/acp"  # Connect to existing iFlow
    )
    
    async with IFlowClient(options) as client:
        await client.send_message("Hello, iFlow!")

asyncio.run(main())
```

**Note:** Manual mode requires you to start iFlow separately:
```bash
iflow --experimental-acp --port 8090
```

### Simple Examples

#### Simple Query

```python
import asyncio
from iflow_sdk import query

async def main():
    response = await query("What is the capital of France?")
    print(response)  # "The capital of France is Paris."

asyncio.run(main())
```

#### Interactive Conversation

```python
import asyncio
from iflow_sdk import IFlowClient, AssistantMessage, TaskFinishMessage

async def chat():
    async with IFlowClient() as client:
        await client.send_message("Explain quantum computing")
        
        async for message in client.receive_messages():
            if isinstance(message, AssistantMessage):
                print(message.chunk.text, end="", flush=True)
            elif isinstance(message, TaskFinishMessage):
                break

asyncio.run(chat())
```

#### Tool Call Control with Agent Information

```python
import asyncio
from iflow_sdk import IFlowClient, IFlowOptions, PermissionMode, ToolCallMessage, TaskFinishMessage, AgentInfo

async def main():
    options = IFlowOptions(permission_mode=PermissionMode.AUTO)
    
    async with IFlowClient(options) as client:
        await client.send_message("Create a file called test.txt")
        
        async for message in client.receive_messages():
            if isinstance(message, ToolCallMessage):
                print(f"Tool requested: {message.tool_name}")
                print(f"Tool status: {message.status}")
                
                # Access agent information
                if message.agent_info:
                    print(f"Agent ID: {message.agent_info.agent_id}")
                    print(f"Task ID: {message.agent_info.task_id}")
                    print(f"Agent Index: {message.agent_info.agent_index}")
                
                # Access tool execution details (added dynamically)
                if hasattr(message, 'args'):
                    print(f"Tool arguments: {message.args}")
                if hasattr(message, 'output'):
                    print(f"Tool output: {message.output}")
                    
            elif isinstance(message, TaskFinishMessage):
                break

asyncio.run(main())
```

#### Working with AgentInfo

```python
import asyncio
from iflow_sdk import AgentInfo, IFlowClient, AssistantMessage, CreateAgentConfig, IFlowOptions, ToolCallMessage


async def agent_info_example():
    # ๅˆ›ๅปบAgent้…็ฝฎ
    agents = [
        CreateAgentConfig(
            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"
        ),
        CreateAgentConfig(
            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"
        )
    ]


    options = IFlowOptions(agents=agents)

    # Use in conversation
    async with IFlowClient(options) as client:
        await client.send_message("$test-writer Write a unit test")

        async for message in client.receive_messages():
            if isinstance(message, ToolCallMessage):
                print(f"tool_name: {message.tool_name}")
                
                if hasattr(message, 'output') and message.output:
                    print(f"output: {message.output}")
                
                if hasattr(message, 'args') and message.args:
                    print(f"args: {message.args}")
                    
            elif isinstance(message, AssistantMessage):
                print(message.chunk.text, end="", flush=True)


asyncio.run(agent_info_example())
```

#### Advanced Protocol Features

```python
import asyncio
from iflow_sdk import IFlowClient, IFlowOptions, AgentInfo
from iflow_sdk.types import (
    ApprovalMode, PermissionMode, SessionSettings, McpServer, EnvVariable,
    HookCommand, HookEventConfig, HookEventType, CommandConfig, CreateAgentConfig
)

async def advanced_features():
    # Configure MCP servers for extended capabilities
    mcp_servers = [
        McpServer(
            name="filesystem",
            command="mcp-server-filesystem",
            args=["--allowed-dirs", "/workspace"],
            env=[EnvVariable(name="DEBUG", value="1")]
        )
    ]
    
    # Configure session settings for fine-grained control
    session_settings = SessionSettings(
        allowed_tools=["read_file", "write_file", "execute_code"],
        system_prompt="You are an expert Python developer",
        permission_mode=ApprovalMode.AUTO_EDIT,  # Auto-approve edits
        max_turns=100
    )
    
    # Set up lifecycle hooks
    hooks = {
        HookEventType.PRE_TOOL_USE: [HookEventConfig(
            hooks=[HookCommand(
                command="echo 'Processing request...'",
                timeout=5
            )]
        )]
    }
    
    # Define custom commands
    commands = [
        CommandConfig(
            name="test",
            content="pytest --verbose"
        )
    ]
    
    # Define custom agents for specialized tasks
    agents = [
        CreateAgentConfig(
            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"
        )
    ]
    
    options = IFlowOptions(
        mcp_servers=mcp_servers,
        session_settings=session_settings,
        hooks=hooks,
        commands=commands,
        agents=agents,
        permission_mode=PermissionMode.AUTO  # Auto-approve tool calls
    )
    
    async with IFlowClient(options) as client:
        await client.send_message("Help me optimize this Python code")
        # Process responses...

asyncio.run(advanced_features())
```

## 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 (tool_name, args, output) and agent information
- **`PlanMessage`**: Structured task plans with priority and status
- **`TaskFinishMessage`**: Task completion signal with stop reason (end_turn, max_tokens, refusal, cancelled)

### Agent Information

- **`AgentInfo`**: Agent metadata extracted from iFlow's agentId format (agent_id, task_id, agent_index, timestamp)

### Convenience Functions

- `query(prompt)`: Simple synchronous query
- `query_stream(prompt)`: Streaming responses
- `query_sync(prompt)`: Synchronous with timeout

## Project Structure

```
iflow-sdk-python/
โ”œโ”€โ”€ src/iflow_sdk/
โ”‚   โ”œโ”€โ”€ __init__.py          # Public API exports
โ”‚   โ”œโ”€โ”€ client.py            # Main IFlowClient implementation
โ”‚   โ”œโ”€โ”€ query.py             # Simple query functions
โ”‚   โ”œโ”€โ”€ types.py             # Type definitions and messages
โ”‚   โ”œโ”€โ”€ raw_client.py        # Raw protocol access
โ”‚   โ””โ”€โ”€ _internal/
โ”‚       โ”œโ”€โ”€ protocol.py      # ACP protocol handler
โ”‚       โ”œโ”€โ”€ transport.py     # WebSocket transport layer
โ”‚       โ””โ”€โ”€ launcher.py      # iFlow process management
โ”œโ”€โ”€ tests/                   # Test suite
โ”‚   โ”œโ”€โ”€ test_basic.py        # Basic functionality tests
โ”‚   โ””โ”€โ”€ test_protocol.py     # Protocol compliance tests
โ”œโ”€โ”€ examples/                # Usage examples
โ”‚   โ”œโ”€โ”€ comprehensive_demo.py
โ”‚   โ”œโ”€โ”€ quick_start.py
โ”‚   โ””โ”€โ”€ advanced_client.py
โ””โ”€โ”€ docs/                    # Documentation
```

## Development

### Running Tests

```bash
# Run all tests
pytest tests/

# Run with coverage
pytest tests/ --cov=src/iflow_sdk
# Run specific test
pytest tests/test_basic.py
```

### Code Quality

```bash
# Format code
black src/ tests/

# Sort imports
isort src/ tests/

# Check style
flake8 src/ tests/
```

## 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 `agent_id` 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](CONTRIBUTING.md) for guidelines.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.


---

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

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/yourusername/iflow-cli-sdk-python",
    "name": "iflow-cli-sdk",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "iFlow Team",
    "author_email": "iFlow Team <iflow@example.com>",
    "download_url": "https://files.pythonhosted.org/packages/7b/4c/aa0fd1e8a4f51124ea228a5d82577bd6b85f87c5c38c526944b61ff53ad0/iflow_cli_sdk-0.1.8.tar.gz",
    "platform": null,
    "description": "# iFlow Python SDK\n\n[![PyPI Version](https://img.shields.io/pypi/v/iflow-cli-sdk)](https://pypi.org/project/iflow-cli-sdk/)\n[![Python Version](https://img.shields.io/badge/python-3.8%2B-blue)](https://www.python.org/downloads/)\n[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)\n[![WebSocket Protocol](https://img.shields.io/badge/protocol-ACP%20v1-orange)](docs/protocol.md)\n\n[English](README.md) | [\u4e2d\u6587](README_CN.md)\n\nA powerful Python 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.\n\n**\u2728 Key Feature: The SDK automatically manages the iFlow process - no manual setup required!**\n\n## Features\n\n- \ud83d\ude80 **Automatic Process Management** - Zero-config setup! SDK auto-starts and manages iFlow CLI\n- \ud83d\udd0c **Smart Port Detection** - Automatically finds available ports, no conflicts\n- \ud83d\udd04 **Bidirectional Communication** - Real-time streaming of messages and responses\n- \ud83d\udee0\ufe0f **Tool Call Management** - Handle and control tool executions with fine-grained permissions\n- \ud83e\udd16 **SubAgent Support** - Track and manage multiple AI agents with `agent_id` propagation\n- \ud83d\udccb **Task Planning** - Receive and process structured task plans\n- \ud83d\udd0d **Raw Data Access** - Debug and inspect protocol-level messages\n- \u26a1 **Async/Await Support** - Modern asynchronous Python with full type hints\n- \ud83c\udfaf **Simple & Advanced APIs** - From one-line queries to complex conversation management\n- \ud83d\udce6 **Full ACP v1 Protocol** - Complete implementation of the Agent Communication Protocol\n- \ud83d\udea6 **Advanced Approval Modes** - Including DEFAULT, AUTO_EDIT, YOLO, and PLAN modes\n- \ud83d\udd17 **MCP Server Integration** - Support for Model Context Protocol servers\n- \ud83e\ude9d **Lifecycle Hooks** - Execute commands at different stages of conversation\n- \ud83c\udfae **Session Settings** - Fine-grained control over model behavior and tools\n- \ud83e\udd16 **Custom Agents** - Define specialized agents with custom prompts and tools\n\n## Installation\n\n### 1. Install iFlow CLI\n\nIf you haven't installed iFlow CLI yet:\n\n**Mac/Linux/Ubuntu:**\n```bash\nbash -c \"$(curl -fsSL https://gitee.com/iflow-ai/iflow-cli/raw/main/install.sh)\"\n```\n\n**Windows:**\n```bash\nnpm install -g @iflow-ai/iflow-cli@latest\n```\n\n### 2. Install the SDK\n\n**Install from PyPI (Recommended):**\n\n```bash\npip install iflow-cli-sdk\n```\n\n**Or install from source:**\n\n```bash\ngit clone https://github.com/yourusername/iflow-cli-sdk-python.git\ncd iflow-cli-sdk-python\npip install -e .\n```\n\n## Quick Start\n\nThe SDK **automatically manages the iFlow process** - no manual setup required!\n\n### Default Usage (Automatic Process Management)\n\n```python\nimport asyncio\nfrom iflow_sdk import IFlowClient\n\nasync def main():\n    # SDK automatically:\n    # 1. Detects if iFlow is installed\n    # 2. Starts iFlow process if not running\n    # 3. Finds an available port\n    # 4. Cleans up on exit\n    async with IFlowClient() as client:\n        await client.send_message(\"Hello, iFlow!\")\n        \n        async for message in client.receive_messages():\n            print(message)\n            # Process messages...\n\nasyncio.run(main())\n```\n\n**No need to manually start iFlow!** The SDK handles everything for you.\n\n### Advanced: Manual Process Control\n\nIf you need to manage iFlow yourself (rare cases):\n\n```python\nimport asyncio\nfrom iflow_sdk import IFlowClient, IFlowOptions\n\nasync def main():\n    # Disable automatic process management\n    options = IFlowOptions(\n        auto_start_process=False,\n        url=\"ws://localhost:8090/acp\"  # Connect to existing iFlow\n    )\n    \n    async with IFlowClient(options) as client:\n        await client.send_message(\"Hello, iFlow!\")\n\nasyncio.run(main())\n```\n\n**Note:** Manual mode requires you to start iFlow separately:\n```bash\niflow --experimental-acp --port 8090\n```\n\n### Simple Examples\n\n#### Simple Query\n\n```python\nimport asyncio\nfrom iflow_sdk import query\n\nasync def main():\n    response = await query(\"What is the capital of France?\")\n    print(response)  # \"The capital of France is Paris.\"\n\nasyncio.run(main())\n```\n\n#### Interactive Conversation\n\n```python\nimport asyncio\nfrom iflow_sdk import IFlowClient, AssistantMessage, TaskFinishMessage\n\nasync def chat():\n    async with IFlowClient() as client:\n        await client.send_message(\"Explain quantum computing\")\n        \n        async for message in client.receive_messages():\n            if isinstance(message, AssistantMessage):\n                print(message.chunk.text, end=\"\", flush=True)\n            elif isinstance(message, TaskFinishMessage):\n                break\n\nasyncio.run(chat())\n```\n\n#### Tool Call Control with Agent Information\n\n```python\nimport asyncio\nfrom iflow_sdk import IFlowClient, IFlowOptions, PermissionMode, ToolCallMessage, TaskFinishMessage, AgentInfo\n\nasync def main():\n    options = IFlowOptions(permission_mode=PermissionMode.AUTO)\n    \n    async with IFlowClient(options) as client:\n        await client.send_message(\"Create a file called test.txt\")\n        \n        async for message in client.receive_messages():\n            if isinstance(message, ToolCallMessage):\n                print(f\"Tool requested: {message.tool_name}\")\n                print(f\"Tool status: {message.status}\")\n                \n                # Access agent information\n                if message.agent_info:\n                    print(f\"Agent ID: {message.agent_info.agent_id}\")\n                    print(f\"Task ID: {message.agent_info.task_id}\")\n                    print(f\"Agent Index: {message.agent_info.agent_index}\")\n                \n                # Access tool execution details (added dynamically)\n                if hasattr(message, 'args'):\n                    print(f\"Tool arguments: {message.args}\")\n                if hasattr(message, 'output'):\n                    print(f\"Tool output: {message.output}\")\n                    \n            elif isinstance(message, TaskFinishMessage):\n                break\n\nasyncio.run(main())\n```\n\n#### Working with AgentInfo\n\n```python\nimport asyncio\nfrom iflow_sdk import AgentInfo, IFlowClient, AssistantMessage, CreateAgentConfig, IFlowOptions, ToolCallMessage\n\n\nasync def agent_info_example():\n    # \u521b\u5efaAgent\u914d\u7f6e\n    agents = [\n        CreateAgentConfig(\n            agentType=\"code-reviewer\",\n            name=\"reviewer\",\n            description=\"Code review specialist\",\n            whenToUse=\"For code review and quality checks\",\n            allowedTools=[\"fs\", \"grep\"],\n            allowedMcps=[\"eslint\", \"prettier\"],\n            systemPrompt=\"You are a code review expert.\",\n            proactive=False,\n            location=\"project\"\n        ),\n        CreateAgentConfig(\n            agentType=\"test-writer\",\n            name=\"tester\",\n            description=\"Test writing specialist\",\n            whenToUse=\"For writing unit and integration tests\",\n            allowedTools=[\"fs\", \"bash\"],\n            systemPrompt=\"You are a test writing expert.\",\n            location=\"project\"\n        )\n    ]\n\n\n    options = IFlowOptions(agents=agents)\n\n    # Use in conversation\n    async with IFlowClient(options) as client:\n        await client.send_message(\"$test-writer Write a unit test\")\n\n        async for message in client.receive_messages():\n            if isinstance(message, ToolCallMessage):\n                print(f\"tool_name: {message.tool_name}\")\n                \n                if hasattr(message, 'output') and message.output:\n                    print(f\"output: {message.output}\")\n                \n                if hasattr(message, 'args') and message.args:\n                    print(f\"args: {message.args}\")\n                    \n            elif isinstance(message, AssistantMessage):\n                print(message.chunk.text, end=\"\", flush=True)\n\n\nasyncio.run(agent_info_example())\n```\n\n#### Advanced Protocol Features\n\n```python\nimport asyncio\nfrom iflow_sdk import IFlowClient, IFlowOptions, AgentInfo\nfrom iflow_sdk.types import (\n    ApprovalMode, PermissionMode, SessionSettings, McpServer, EnvVariable,\n    HookCommand, HookEventConfig, HookEventType, CommandConfig, CreateAgentConfig\n)\n\nasync def advanced_features():\n    # Configure MCP servers for extended capabilities\n    mcp_servers = [\n        McpServer(\n            name=\"filesystem\",\n            command=\"mcp-server-filesystem\",\n            args=[\"--allowed-dirs\", \"/workspace\"],\n            env=[EnvVariable(name=\"DEBUG\", value=\"1\")]\n        )\n    ]\n    \n    # Configure session settings for fine-grained control\n    session_settings = SessionSettings(\n        allowed_tools=[\"read_file\", \"write_file\", \"execute_code\"],\n        system_prompt=\"You are an expert Python developer\",\n        permission_mode=ApprovalMode.AUTO_EDIT,  # Auto-approve edits\n        max_turns=100\n    )\n    \n    # Set up lifecycle hooks\n    hooks = {\n        HookEventType.PRE_TOOL_USE: [HookEventConfig(\n            hooks=[HookCommand(\n                command=\"echo 'Processing request...'\",\n                timeout=5\n            )]\n        )]\n    }\n    \n    # Define custom commands\n    commands = [\n        CommandConfig(\n            name=\"test\",\n            content=\"pytest --verbose\"\n        )\n    ]\n    \n    # Define custom agents for specialized tasks\n    agents = [\n        CreateAgentConfig(\n            agentType=\"python-expert\",\n            whenToUse=\"For Python development tasks\",\n            allowedTools=[\"edit_file\", \"run_python\", \"debug\"],\n            systemPrompt=\"You are a Python expert focused on clean, efficient code\",\n            name=\"Python Expert\",\n            description=\"Specialized in Python development\"\n        )\n    ]\n    \n    options = IFlowOptions(\n        mcp_servers=mcp_servers,\n        session_settings=session_settings,\n        hooks=hooks,\n        commands=commands,\n        agents=agents,\n        permission_mode=PermissionMode.AUTO  # Auto-approve tool calls\n    )\n    \n    async with IFlowClient(options) as client:\n        await client.send_message(\"Help me optimize this Python code\")\n        # Process responses...\n\nasyncio.run(advanced_features())\n```\n\n## API Reference\n\n### Core Classes\n\n- **`IFlowClient`**: Main client for bidirectional communication\n- **`IFlowOptions`**: Configuration options\n- **`RawDataClient`**: Access to raw protocol data\n\n### Message Types\n\n- **`AssistantMessage`**: AI assistant responses with optional agent information\n- **`ToolCallMessage`**: Tool execution requests with execution details (tool_name, args, output) and agent information\n- **`PlanMessage`**: Structured task plans with priority and status\n- **`TaskFinishMessage`**: Task completion signal with stop reason (end_turn, max_tokens, refusal, cancelled)\n\n### Agent Information\n\n- **`AgentInfo`**: Agent metadata extracted from iFlow's agentId format (agent_id, task_id, agent_index, timestamp)\n\n### Convenience Functions\n\n- `query(prompt)`: Simple synchronous query\n- `query_stream(prompt)`: Streaming responses\n- `query_sync(prompt)`: Synchronous with timeout\n\n## Project Structure\n\n```\niflow-sdk-python/\n\u251c\u2500\u2500 src/iflow_sdk/\n\u2502   \u251c\u2500\u2500 __init__.py          # Public API exports\n\u2502   \u251c\u2500\u2500 client.py            # Main IFlowClient implementation\n\u2502   \u251c\u2500\u2500 query.py             # Simple query functions\n\u2502   \u251c\u2500\u2500 types.py             # Type definitions and messages\n\u2502   \u251c\u2500\u2500 raw_client.py        # Raw protocol access\n\u2502   \u2514\u2500\u2500 _internal/\n\u2502       \u251c\u2500\u2500 protocol.py      # ACP protocol handler\n\u2502       \u251c\u2500\u2500 transport.py     # WebSocket transport layer\n\u2502       \u2514\u2500\u2500 launcher.py      # iFlow process management\n\u251c\u2500\u2500 tests/                   # Test suite\n\u2502   \u251c\u2500\u2500 test_basic.py        # Basic functionality tests\n\u2502   \u2514\u2500\u2500 test_protocol.py     # Protocol compliance tests\n\u251c\u2500\u2500 examples/                # Usage examples\n\u2502   \u251c\u2500\u2500 comprehensive_demo.py\n\u2502   \u251c\u2500\u2500 quick_start.py\n\u2502   \u2514\u2500\u2500 advanced_client.py\n\u2514\u2500\u2500 docs/                    # Documentation\n```\n\n## Development\n\n### Running Tests\n\n```bash\n# Run all tests\npytest tests/\n\n# Run with coverage\npytest tests/ --cov=src/iflow_sdk\n# Run specific test\npytest tests/test_basic.py\n```\n\n### Code Quality\n\n```bash\n# Format code\nblack src/ tests/\n\n# Sort imports\nisort src/ tests/\n\n# Check style\nflake8 src/ tests/\n```\n\n## Protocol Support\n\nThe SDK implements the Agent Communication Protocol (ACP) v1 with full extension support, including:\n\n- **Session Management**: Create, load, and manage conversation sessions with advanced settings\n- **Message Types**: \n  - `agent_message_chunk` - Assistant responses\n  - `agent_thought_chunk` - Internal reasoning\n  - `tool_call` / `tool_call_update` - Tool execution lifecycle\n  - `plan` - Structured task planning with priorities\n  - `user_message_chunk` - User message echoing\n  - `stop_reason` - Task completion with reason (end_turn, max_tokens, refusal, cancelled)\n- **Authentication**: Built-in iFlow authentication with token support\n- **File System Access**: Read/write file permissions with configurable limits\n- **SubAgent Support**: Full `agent_id` tracking and management\n- **Advanced Features**:\n  - **MCP Servers**: Integrate Model Context Protocol servers for extended capabilities\n  - **Approval Modes**: DEFAULT, AUTO_EDIT, YOLO (auto-approve all), PLAN modes\n  - **Session Settings**: Control allowed tools, system prompts, model selection\n  - **Lifecycle Hooks**: Execute commands at different conversation stages\n  - **Custom Commands**: Define and execute custom commands\n  - **Specialized Agents**: Create agents with specific expertise and tool access\n\n## Contributing\n\nContributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n\n---\n\nBuilt with \u2764\ufe0f for the AI development community\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python SDK for iFlow CLI - AI Agent Integration",
    "version": "0.1.8",
    "project_urls": {
        "Documentation": "https://docs.iflow.ai/sdk/python",
        "Homepage": "https://github.com/iflow/iflow-sdk-python",
        "Issues": "https://github.com/iflow/iflow-sdk-python/issues",
        "Repository": "https://github.com/iflow/iflow-sdk-python"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7b4caa0fd1e8a4f51124ea228a5d82577bd6b85f87c5c38c526944b61ff53ad0",
                "md5": "39f3bb3613e464b259b705f37178d4fa",
                "sha256": "6fd03defa6cc9dd9b4b723f9bda5d17f7a0b575eaa0dc8ffb2066372e3d2bbc9"
            },
            "downloads": -1,
            "filename": "iflow_cli_sdk-0.1.8.tar.gz",
            "has_sig": false,
            "md5_digest": "39f3bb3613e464b259b705f37178d4fa",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 38869,
            "upload_time": "2025-10-27T07:32:38",
            "upload_time_iso_8601": "2025-10-27T07:32:38.796763Z",
            "url": "https://files.pythonhosted.org/packages/7b/4c/aa0fd1e8a4f51124ea228a5d82577bd6b85f87c5c38c526944b61ff53ad0/iflow_cli_sdk-0.1.8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-27 07:32:38",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "yourusername",
    "github_project": "iflow-cli-sdk-python",
    "github_not_found": true,
    "lcname": "iflow-cli-sdk"
}
        
Elapsed time: 3.52762s