TypeScript SDK
概述
iFlow SDK是用于与iFlow CLI进行编程交互的SDK,通过他可以快速将iFlow CLI集成到你的业务系统中,结合workflow等智能体扩展,允许开发者构建具有对话、工具执行和任务规划能力的 AI 驱动应用程序,让业务系统具备AI的能力。 目前已支持Python、Java、TypeScript、Android版本。
✨ 核心特性:SDK 自动管理 iFlow 进程 - 无需手动配置!
系统要求
- Node.js: 22.0 或更高版本
- TypeScript: 4.5 或更高版本(可选,但推荐)
- iFlow CLI: 0.2.24 或更高版本
- 操作系统: Windows、macOS、Linux
安装
npm install --save @iflow-ai/iflow-cli-sdk
快速开始
基础示例
SDK 会自动检测并启动 iFlow 进程,无需手动配置:
import { IFlowClient, MessageType } from "@iflow-ai/iflow-cli-sdk";
async function main() {
const client = new IFlowClient();
try {
// SDK 自动处理:
// 1. 检测 iFlow 是否已安装
// 2. 启动 iFlow 进程(如果未运行)
// 3. 查找可用端口并建立连接
await client.connect();
await client.sendMessage("你好,iFlow!");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.ASSISTANT && message.chunk.text) {
console.log(message.chunk.text);
} else if (message.type === MessageType.TASK_FINISH) {
break;
}
}
} finally {
await client.disconnect();
}
}
main().catch(console.error);
简单查询
最简单的使用方式是通过 query 函数:
import { query } from "@iflow-ai/iflow-cli-sdk";
async function main() {
const response = await query("法国的首都是哪里?");
console.log(response); // 输出:法国的首都是巴黎。
}
main().catch(console.error);
核心概念
IFlowClient
IFlowClient 是与 iFlow CLI 交互的主要接口,管理 WebSocket 连接的生命周期:
import { IFlowClient, IFlowOptions } from "@iflow-ai/iflow-cli-sdk";
async function main() {
// 使用默认配置(自动管理进程)
const client = new IFlowClient();
try {
await client.connect();
await client.sendMessage("你的问题");
for await (const message of client.receiveMessages()) {
// 处理消息
}
} finally {
await client.disconnect();
}
// 使用自定义配置
const customOptions: IFlowOptions = {
url: "ws://localhost:8090/acp", // WebSocket URL
autoStartProcess: true, // 自动启动 iFlow
timeout: 30000, // 超时时间(毫秒)
};
const customClient = new IFlowClient(customOptions);
try {
await customClient.connect();
await customClient.sendMessage("你的问题");
for await (const message of customClient.receiveMessages()) {
// 处理消息
}
} catch {
await customClient.disconnect();
}
}
main().catch(console.error);
消息类型
SDK 支持多种消息类型,对应 iFlow 协议的不同响应:
AssistantMessage - AI 助手响应
包含 AgentInfo 支持,可以获取代理的详细信息:
import { IFlowClient, MessageType, AgentInfo } from "@iflow-ai/iflow-cli-sdk";
async function handleAssistantMessage() {
const client = new IFlowClient();
try {
await client.connect();
await client.sendMessage("请介绍一下 TypeScript");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.ASSISTANT && message.chunk.text) {
console.log(message.chunk.text);
// 访问代理信息(如果有)
if (message.agentInfo) {
console.log(`代理 ID: ${message.agentInfo.agentId}`);
if (message.agentInfo.taskId) {
console.log(`任务 ID: ${message.agentInfo.taskId}`);
}
if (message.agentInfo.agentIndex) {
console.log(`代理索引: ${message.agentInfo.agentIndex}`);
}
}
} else if (message.type === MessageType.TASK_FINISH) {
break;
}
}
} finally {
await client.disconnect();
}
}
handleAssistantMessage().catch(console.error);
ToolCallMessage - 工具调用
工具调用消息现在也包含 AgentInfo 信息和工具名称:
import { IFlowClient, MessageType, ToolCallStatus } from "@iflow-ai/iflow-cli-sdk";
async function handleToolCalls() {
const client = new IFlowClient();
try {
await client.connect();
// 注意:这个示例演示如何查看工具调用消息
// iFlow 会要求提供完整路径和内容来创建文件
await client.sendMessage("列出当前目录的文件");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.TOOL_CALL) {
console.log(`状态: ${message.status}`);
// 新增:工具名称
if (message.toolName) {
console.log(`工具名称: ${message.toolName}`);
}
// 访问代理信息
if (message.agentInfo) {
console.log(`代理ID: ${message.agentInfo.agentId}`);
}
} else if (message.type === MessageType.TASK_FINISH) {
break;
}
}
} finally {
await client.disconnect();
}
}
handleToolCalls().catch(console.error);
PlanMessage - 任务计划
import { IFlowClient, MessageType } from "@iflow-ai/iflow-cli-sdk";
async function showPlan() {
const client = new IFlowClient();
try {
await client.connect();
await client.sendMessage("帮我创建一个 TypeScript 项目结构");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.PLAN) {
console.log("执行计划:");
for (const entry of message.entries) {
const statusIcon = entry.status === "completed" ? "✅" : "⏳";
console.log(`${statusIcon} [${entry.priority}] ${entry.content}`);
}
} else if (message.type === MessageType.TASK_FINISH) {
break;
}
}
} finally {
await client.disconnect();
}
}
showPlan().catch(console.error);
TaskFinishMessage - 任务完成
import { IFlowClient, MessageType, StopReason } from "@iflow-ai/iflow-cli-sdk";
async function checkCompletion() {
const client = new IFlowClient();
try {
await client.connect();
await client.sendMessage("计算 1+1");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.ASSISTANT && message.chunk.text) {
process.stdout.write(message.chunk.text);
} else if (message.type === MessageType.TASK_FINISH) {
console.log(); // 换行
if (message.stopReason === StopReason.END_TURN) {
console.log("任务正常完成");
} else if (message.stopReason === StopReason.MAX_TOKENS) {
console.log("达到最大令牌限制");
}
break; // TaskFinishMessage 表示对话结束
}
}
} finally {
await client.disconnect();
}
}
checkCompletion().catch(console.error);
常见用例
交互式聊天机器人
import * as readline from "readline";
import { IFlowClient, MessageType } from "@iflow-ai/iflow-cli-sdk";
async function chatbot() {
console.log("iFlow 聊天机器人 (输入 'quit' 退出)");
console.log("-".repeat(50));
const client = new IFlowClient();
try {
await client.connect();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
while (true) {
const userInput = await new Promise<string>((resolve) => {
rl.question("\n你: ", resolve);
});
if (userInput.toLowerCase() === "quit" || userInput.toLowerCase() === "exit" || userInput.toLowerCase() === "q") {
console.log("再见!");
break;
}
await client.sendMessage(userInput);
process.stdout.write("iFlow: ");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.ASSISTANT && message.chunk.text) {
process.stdout.write(message.chunk.text);
} else if (message.type === MessageType.TASK_FINISH) {
console.log(); // 换行
break;
}
}
}
rl.close();
} finally {
await client.disconnect();
}
}
chatbot().catch(console.error);
高级配置
手动进程管理
如果需要手动管理 iFlow 进程:
import { IFlowClient, MessageType } from "@iflow-ai/iflow-cli-sdk";
async function manualProcessExample() {
const client = new IFlowClient({
autoStartProcess: false, // 禁用自动进程管理
url: "ws://localhost:8090/acp", // 连接到已存在的 iFlow
});
try {
await client.connect();
await client.sendMessage("你的问题");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.ASSISTANT && message.chunk.text) {
process.stdout.write(message.chunk.text);
} else if (message.type === MessageType.TASK_FINISH) {
break;
}
}
} finally {
await client.disconnect();
}
}
manualProcessExample().catch(console.error);
注意 手动模式需要您单独启动 iFlow:
iflow --experimental-acp --port 8090
错误处理
SDK 提供了详细的错误处理机制:
import { IFlowClient, ConnectionError, TimeoutError, MessageType } from "@iflow-ai/iflow-cli-sdk";
async function errorHandlingExample() {
const client = new IFlowClient();
try {
await client.connect();
await client.sendMessage("测试");
for await (const message of client.receiveMessages()) {
if (message.type === MessageType.ASSISTANT && message.chunk.text) {
console.log(message.chunk.text);
} else if (message.type === MessageType.TASK_FINISH) {
break;
}
}
} catch (error) {
if (error instanceof ConnectionError) {
console.error(`连接错误: ${error.message}`);
} else if (error instanceof TimeoutError) {
console.error(`超时错误: ${error.message}`);
} else {
console.error(`未知错误: ${error}`);
}
} finally {
await client.disconnect();
}
}
errorHandlingExample().catch(console.error);
API 参考
核心类
| 类名 | 描述 |
|---|---|
IFlowClient | 主客户端类,管理与 iFlow 的连接 |
RawDataClient | 访问原始协议数据的客户端 |
消息类型
| 消息类型 | 描述 | 主要属性 |
|---|---|---|
AssistantMessage | AI 助手的文本响应 | chunk.text, agentId, agentInfo |
ToolCallMessage | 工具执行请求和状态 | label, status, toolName, agentInfo |
PlanMessage | 结构化任务计划 | entries (包含 content, priority, status) |
TaskFinishMessage | 任务完成信号 | stopReason |
UserMessage | 用户消息 | chunks |
ErrorMessage | 错误消息 | code, message |
AgentInfo - 代理信息
AgentInfo 类型展示了从 iFlow 代理 ID 解析的详细信息:
interface AgentInfo {
agentId: string; // 完整的代理 ID
agentIndex?: number; // 代理在任务中的索引
taskId?: string; // 任务或实例 ID
timestamp?: number; // 创建时间戳
}
配置选项
IFlowOptions 接口提供了丰富的配置选项:
interface IFlowOptions {
url?: string; // WebSocket URL
cwd?: string; // 工作目录
timeout?: number; // 超时时间(毫秒)
logLevel?: "DEBUG" | "INFO" | "WARN" | "ERROR"; // 日志级别
processStartPort?: number; // 进程启动端口
autoStartProcess?: boolean; // 自动启动进程
authMethodId?: string; // 认证方法ID
authMethodInfo?: AuthMethodInfo; // 认证信息
mcpServers?: MCPServerConfig[]; // MCP 服务器配置
hooks?: HookConfigs; // 钩子配置
commands?: CommandConfig[]; // 命令配置
agents?: SubAgentConfig[]; // 子代理配置
sessionSettings?: SessionSettings; // 会话设置
permissionMode?: "auto" | "manual" | "selective"; // 权限模式
autoApproveTypes?: string[]; // 自动批准类型
fileAccess?: boolean; // 文件访问权限
fileMaxSize?: number; // 文件最大大小
fileReadOnly?: boolean; // 只读模式
fileAllowedDirs?: string[]; // 允许的目录
}
interface AuthMethodInfo {
apiKey?: string;
baseUrl?: string;
modelName?: string;
}
interface MCPServerConfig {
name: string;
command: string;
args: string[];
env: { name: string; value: string }[];
}
interface CommandConfig {
name: string;
content: string;
}
interface SubAgentConfig {
agentType: string;
whenToUse: string;
allowedTools: string[];
systemPrompt: string;
name?: string;
description?: string;
allowedMcps?: string[];
proactive?: boolean;
location?: "global" | "project";
model?: string;
isInheritTools?: boolean;
isInheritMcps?: boolean;
}
interface SessionSettings {
system_prompt?: string;
append_system_prompt?: string;
allowed_tools?: string[];
disallowed_tools?: string[];
permission_mode?: "default" | "autoEdit" | "yolo" | "plan";
max_turns?: number;
add_dirs?: string[];
}
故障排除
连接问题
如果遇到连接错误,请检查:
-
iFlow 是否已安装
iflow --version -
端口是否被占用
# Linux/Mac
lsof -i :8090
# Windows
netstat -an | findstr :8090 -
手动测试连接
iflow --experimental-acp --port 8090
超时问题
对于长时间运行的任务,可以增加超时时间:
import { IFlowClient, IFlowOptions } from "@iflow-ai/iflow-cli-sdk";
const options: IFlowOptions = {
timeout: 600000, // 10分钟超时
};
const client = new IFlowClient(options);
日志调试
启用详细日志以便调试:
import { IFlowClient, IFlowOptions } from "@iflow-ai/iflow-cli-sdk";
const options: IFlowOptions = {
logLevel: "DEBUG",
};
const client = new IFlowClient(options);