infiAgent JSONL流式模式实战:从事件协议到构建你自己的VS Code AI插件
infiAgent JSONL流式模式实战:从事件协议到构建你自己的VS Code AI插件
infiAgent(MLA V3)是一个支持无限时长任务的 AI Agent 框架,它内置的 JSONL 流式模式能把 Agent 的每一步执行实时转化为机器可读的 JSON Lines 事件流——这是构建 VS Code AI 插件、桌面应用或 Web 面板的核心接口。本文带你 5 分钟读懂事件协议,并动手搭一个属于自己的 VS Code Agent 插件。
为什么需要 JSONL 流式模式 🤔
传统 Agent 工具只往控制台打印人类可读的文本,外部程序想"看懂"Agent 在干什么,只能靠脆弱的正则解析。infiAgent 的方案是:
- stdout 只输出 JSON:每行一个 JSON 事件,程序可直接
JSON.parse - 日志走 stderr:调试信息、警告全部重定向,不污染事件流
- 观察者模式解耦:Agent 执行器只负责"生产事件",打印到控制台、写 JSONL 流、推送 WebSocket 都只是不同的"事件处理器",互不干扰
这套设计让同一份 Agent 内核,既能跑 CLI、能驱动 Electron 桌面端,也能被 Web UI 或你自写的 VS Code 插件消费。
一键启用:JSONL 模式快速上手
1. 安装 infiAgent
git clone https://gitcode.com/gh_mirrors/inf/infiAgent
cd infiAgent
pip install -e .
2. 用 --jsonl 启动任务
在任意工作空间下执行:
mla-agent \
--task_id $(pwd) \
--user_input "优化这段代码的性能" \
--jsonl 2>/dev/null
参数说明(详见 start.py):
--jsonl:启用 JSONL 事件输出模式,专为 IDE 集成设计--task_id:任务工作目录绝对路径,同一目录共享同一份 Agent 记忆2>/dev/null:丢弃 stderr 上的普通日志,只留干净的事件流
你会看到类似这样的输出:
{"type":"start","call_id":"c-1760936557-474c43","project":"~/project","agent":"alpha_agent","task":"优化..."}
{"type":"token","text":"[alpha_agent] Analyzing code..."}
{"type":"progress","phase":"execution","pct":30}
{"type":"tool_call","name":"code_analyzer","arguments":{...}}
{"type":"result","ok":true,"summary":"Optimization complete"}
{"type":"end","status":"ok","duration_ms":5432}
3. 开启双向控制通道
--jsonl 模式下,Agent 会额外监听 stdin:当你需要人机交互(HIL)确认时,可以把一行 JSON 写回进程,任务即会继续执行:
{"type":"hil_response","hil_id":"...","response":"确认继续"}
这就是"Agent 提问 → 你的 UI 弹窗 → 用户回答 → 任务续跑"的完整闭环,实现见 start.py。
读懂事件协议:三类事件一览
事件协议完整定义在 docs/EVENT_SCHEMA.md,核心规则是 phase.domain.action 三段式命名(如 run.tool.start = 执行阶段 → 工具域 → 开始动作)。落到 JSONL 流上,消费端主要关心这几类 type:
| 事件类型 | 触发时机 | 关键字段 |
|---|---|---|
start |
任务启动 | call_id、agent、task |
token |
流式文本输出 | text |
progress |
进度更新 | phase、pct |
tool_call / tool_result |
工具调用与结果 | name、arguments、status |
thinking_start / thinking_end |
Agent 自我规划 | agent、result |
human_in_loop |
等待人工确认 | hil_id、title、ui |
result / end |
任务结果与收尾 | ok、summary、duration_ms |
发射逻辑集中在两处:
- core/event_handlers.py 中的
JsonlStreamHandler:把内部 Agent 事件自动转成上述 JSONL 格式,纯展示类系统事件会被自动过滤 - utils/event_emitter.py 中的
EventEmitter:负责真正写 stdout,并保证flush()后立即对消费端可见
💡 扩展新事件非常简单:在 core/events.py 定义 dataclass,JsonlStreamHandler 会自动序列化,通常无需改动任何消费端代码。
真实案例:infiAgent 桌面端如何消费事件流
infiAgent 自带的 Electron 桌面应用就是 JSONL 模式的"官方消费者",其解析逻辑值得直接借鉴(desktop_app/src/main.js):
pythonProcess.stdout.on('data', (data) => {
buffer += data.toString();
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // 处理跨 chunk 的不完整行
for (const line of lines) {
if (!line.trim()) continue;
try {
const evt = JSON.parse(line);
mainWindow.webContents.send('agent-event', evt); // 推给渲染层
} catch (e) {
mainWindow.webContents.send('agent-log', line); // 非 JSON 当日志
}
}
});
两个关键细节:行缓冲拼接(buffer 处理 TCP/管道 chunk 边界)和 JSON 解析失败兜底(非 JSON 行降级为普通日志,绝不崩溃)。
Web UI 走的是另一条等价路径:web_ui/server/sdk_worker.py 每个任务起一个独立进程,直接调用 Python SDK 并把 on_event 回调映射为 JSONL 事件输出,同样保证 stdout 机器可读。
动手实践:写一个最小 VS Code AI 插件
有了 runAgent 客户端和事件协议,一个可用的插件骨架只需三步。
第 1 步:封装 Agent 客户端
import { spawn } from 'child_process';
function runAgent(workspace: string, task: string,
onEvent: (e: any) => void): Promise<any> {
return new Promise((resolve, reject) => {
const child = spawn('mla-agent', [
'--task_id', workspace, '--user_input', task, '--jsonl'
]);
let buffer = '';
child.stdout.on('data', (d) => {
buffer += d.toString();
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
try {
const evt = JSON.parse(line);
onEvent(evt);
if (evt.type === 'end') resolve(evt);
else if (evt.type === 'error') reject(new Error(evt.text));
} catch { /* 非 JSON 行忽略 */ }
}
});
child.stderr.pipe(process.stderr);
});
}
第 2 步:注册命令 + 进度通知
import * as vscode from 'vscode';
import { runAgent } from './mla-client';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand(
'mla.executeTask', async () => {
const workspace = vscode.workspace.workspaceFolders?.[0].uri.fsPath;
const input = await vscode.window.showInputBox({
prompt: '输入要交给 Agent 的任务'
});
if (!workspace || !input) return;
await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification,
title: 'infiAgent 执行中', cancellable: true },
async (progress) => {
await runAgent(workspace, input, (evt) => {
if (evt.type === 'token') {
vscode.window.showInformationMessage(evt.text);
} else if (evt.type === 'progress') {
progress.report({ increment: evt.pct });
}
});
});
}));
}
第 3 步:接入 HIL 人机交互
当插件收到 human_in_loop 事件时,弹 vscode.window.showQuickPick 让用户选择,然后把选择写回子进程 stdin:
child.stdin.write(JSON.stringify(
{ type: 'hil_response', hil_id: evt.hil_id, response: userChoice }
) + '\n');
至此,你的 VS Code 命令面板里就有了一个能实时流式输出、支持工具卡片展示、可交互确认的 Agent 插件。完整的参考结构见 README.md 的 "VS Code Extension Example" 章节。
进阶:SDK 事件流与 stream_llm_tokens 🚀
除了 CLI --jsonl,Python SDK 也提供等价的实时事件通道,适合把 Agent 嵌入任意后端服务:
from infiagent import infiagent
agent = infiagent(user_data_root="/path/to/my_project/runtime")
def on_event(event: dict):
print(event["event_type"], event["payload"])
result = agent.run(
"整理本周日志并生成总结",
task_id="/abs/path/to/tasks/demo_task",
on_event=on_event, # 实时消费事件
stream_llm_tokens=True, # 额外透出 token 级事件
)
开启 stream_llm_tokens=True 后会多出 run.llm.token、run.thinking.token 等细粒度事件。⚠️ 注意一个坑:如果某轮流式输出中途失败触发重试,SDK 会先发 run.llm.reset——消费端收到 reset 后必须清空正在拼接的文本段,否则会混入重试前的残留内容。完整参数说明见 docs/SDK_GUIDE.md。
常见踩坑清单 ⚠️
| 问题 | 原因与解法 |
|---|---|
| 事件流里混入普通日志 | 忘了 2>/dev/null;JSONL 模式把所有 print 重定向到了 stderr |
| JSON 解析报错 | 未按行缓冲拼接 chunk,直接对每个 data 事件 parse |
| 任务卡在等待状态 | Agent 触发了 human_in_loop,需通过 stdin 回写 hil_response |
| 同一任务重复启动失败 | 同一 task_id 已有进程在跑,先 reset_task 或换目录 |
总结
infiAgent 的 JSONL 流式模式做对了一件事:把"Agent 执行过程"变成了一门稳定的机器语言。理解了 start → token/tool_call → result → end 这条事件链和 stdin/stdout 双向通道,你就能用不到百行代码,把同一个无限时长 Agent 内核接进 VS Code、Electron、Web 面板或任何你想象的界面里。
📌 延伸阅读:
- 事件协议完整规范:docs/EVENT_SCHEMA.md
- SDK 全量 API:docs/SDK_GUIDE.md
- CLI 参数速查:docs/CLI_GUIDE.md
- JSONL 处理器实现:core/event_handlers.py


