async function runAgentTask(taskId: string, userGoal: string) {
// 01 + 02. Context 拼装:只加载必要系统规则、RAG 证据与用户记忆
const evidence = await retrieveRunbook(userGoal);
const memory = await loadOnCallPreferences(taskId);
const messages: Message[] = buildContext({ userGoal, evidence, memory });
for (let step = 1; step <= MAX_STEPS; step++) {
// 03. LLM 推理:无状态调用,决定直接回答还是发起工具调用
const reply = await callModel({ messages, tools: declaredTools });
messages.push(reply.assistantMessage);
if (reply.stopReason === "end_turn") {
await saveCheckpoint(taskId, { step, status: "done", messages });
return reply.finalText;
}
for (const call of reply.toolCalls) {
// 04. Harness 护栏:校验参数 Schema、权限等级与高危人工审批
const decision = await harness.check(call, { step, budgetRemaining: MAX_STEPS - step });
if (!decision.allowed) {
messages.push(toolError(call.id, decision.reason));
continue;
}
// 05. 工具执行(本地函数或 MCP Server),结果写回下一轮上下文
const output = await executeTool(call.name, call.args, { idempotencyKey: `${taskId}:${step}:${call.id}` });
messages.push(toolResult(call.id, truncateForBudget(output)));
}
// 06. 状态持久化(检查点)与按需上下文压缩(信息层)
await saveCheckpoint(taskId, { step, status: "running", messages });
if (estimateTokens(messages) > COMPACT_THRESHOLD) compactOldTurns(messages);
}
throw new Error("Exceeded MAX_STEPS budget");
}
每个独立模块的可运行 TypeScript 代码均托管在同仓 examples/ 目录 ↗,后续章节会逐一拆解每一行的边界条件。