后台任务
使用 Bash runInBackground 异步执行长任务、管理后台注册表与主动取消。
开发过程中经常遇到长时间运行的命令(如 npm run dev 启动本地开发服务、耗时数分钟的测试套件构建、或者是代码库大范围静态分析)。将这类命令放到前台会阻塞 Agent 与用户的实时对话流。
SDK 支持后台异步作业管理机制。
启动后台命令
当 Agent 发起 Bash 工具调用并指定 runInBackground: true 时,命令将在工作区后台启动并立即返回:
// 模型发起的调用参数示例
{
command: "bun run dev",
runInBackground: true
}
工具调用在确认子进程成功派生后即刻向模型返回就绪状态,附带后台作业的 agentId 和 title,前台对话随后继续进行。
共享后台任务注册表(BackgroundAgentStore)
为了在同一个会话的多次连续调用间追踪并管理这些后台作业,宿主可以传入 BackgroundAgentStore 实例:
import { createCodingAgent, createBackgroundAgentStore } from "jai-coding-agent";
// 创建内存中的后台任务注册表
const backgroundAgents = createBackgroundAgentStore();
const agent = (await createCodingAgent({
model: "anthropic/claude-3-7-sonnet",
cwd: process.cwd(),
backgroundAgents, // 挂载共享注册表
})).value;
挂载该 Store 后,即使启动该命令的当前这一轮 prompt() 已经执行结束,后台作业依然由 Store 持续监管。
监听后台任务结算(background_agent_end)
当后台进程执行完毕、抛错退出或被主动终止时,SDK 会通过事件流派发 background_agent_end:
agent.subscribe((event) => {
if (event.type === "background_agent_end") {
console.log(`[后台任务结算] ${event.title}`);
console.log(`状态: ${event.status}`); // "complete" | "error" | "stopped"
console.log(`关联 toolCallId: ${event.toolCallId}`);
}
});
主动停止后台任务
宿主可以通过 toolCallId 主动中止指定的后台进程:
// 中止指定的后台作业
const result = await agent.stopBackgroundAgent(toolCallId);
if (result.isOk() && result.value.stopped) {
console.log("后台任务已成功终止");
}