fix(plan-execute): align orchestrator turn budget with max_iterations and preserve partial output on iteration limits

This commit is contained in:
Sycun 2026-11-30 22:25:46 +08:00
parent 41aea97735
commit 3ad176b926
10 changed files with 274 additions and 58 deletions

View File

@ -384,7 +384,7 @@ multi_agent:
enabled: true enabled: true
robot_default_agent_mode: single # 企微/钉钉/飞书机器人默认:single | deep | plan_execute | supervisor robot_default_agent_mode: single # 企微/钉钉/飞书机器人默认:single | deep | plan_execute | supervisor
batch_use_multi_agent: false # true 时「批量任务」队列中每个子任务也走 Pi 多代理(成本更高) batch_use_multi_agent: false # true 时「批量任务」队列中每个子任务也走 Pi 多代理(成本更高)
# plan_execute 专用:execute↔replan 外层循环上限,0 表示 原生默认 10。主/子代理 ReAct 轮次见 agent.max_iterations。 # plan_execute 专用:向 executor 委派的外层步数预算上限;0 表示不单独限制(主/子代理 ReAct 轮次统一由 agent.max_iterations 控制)。
plan_execute_loop_max_iterations: 0 plan_execute_loop_max_iterations: 0
sub_agent_user_context_max_runes: 0 # 子代理 task 描述中注入用户原文;0=不截断(默认),>0=总字符上限,负数=禁用 sub_agent_user_context_max_runes: 0 # 子代理 task 描述中注入用户原文;0=不截断(默认),>0=总字符上限,负数=禁用
without_general_sub_agent: false # false 时保留 Deep 内置 general-purpose 子代理 without_general_sub_agent: false # false 时保留 Deep 内置 general-purpose 子代理

View File

@ -77,7 +77,7 @@ func FromRunResult(db *database.DB, result *multiagent.RunResult, in Input) Deci
} }
d := Decide(db, in) d := Decide(db, in)
if result != nil { if result != nil {
if d.CompletionReason == multiagent.ReasonUnfinishedPlan { if !d.Finalizable && len(result.UnfinishedPlanSteps) > 0 {
d.UnfinishedPlanSteps = result.UnfinishedPlanSteps d.UnfinishedPlanSteps = result.UnfinishedPlanSteps
} }
result.Finalized = d.Finalized result.Finalized = d.Finalized
@ -127,7 +127,9 @@ func Decide(db *database.DB, in Input) Decision {
if d.CompletionReason == ReasonVerified { if d.CompletionReason == ReasonVerified {
d.CompletionReason = status d.CompletionReason = status
} }
if d.CompletionReason == multiagent.ReasonUnfinishedPlan && isEmptyCandidate(text) { if (d.CompletionReason == multiagent.ReasonUnfinishedPlan ||
d.CompletionReason == multiagent.ReasonIterationLimit ||
d.CompletionReason == multiagent.ReasonPlanningIterationLimit) && isEmptyCandidate(text) {
d.FinalText = "" d.FinalText = ""
d.CandidateResponseLen = 0 d.CandidateResponseLen = 0
} }

View File

@ -41,6 +41,7 @@ type OrchestratorMarkdown struct {
DisplayName string DisplayName string
Description string Description string
Instruction string Instruction string
MaxIterations int
} }
// MarkdownDirLoad 一次扫描 agents 目录的结果(子代理不含主代理文件)。 // MarkdownDirLoad 一次扫描 agents 目录的结果(子代理不含主代理文件)。
@ -248,6 +249,7 @@ func orchestratorFromParsed(filename string, fm FrontMatter, body string) (*Orch
DisplayName: display, DisplayName: display,
Description: strings.TrimSpace(fm.Description), Description: strings.TrimSpace(fm.Description),
Instruction: strings.TrimSpace(body), Instruction: strings.TrimSpace(body),
MaxIterations: fm.MaxIterations,
}, nil }, nil
} }
@ -260,6 +262,7 @@ func orchestratorConfigFromOrchestrator(o *OrchestratorMarkdown) config.MultiAge
Name: o.DisplayName, Name: o.DisplayName,
Description: o.Description, Description: o.Description,
Instruction: o.Instruction, Instruction: o.Instruction,
MaxIterations: o.MaxIterations,
Kind: "orchestrator", Kind: "orchestrator",
} }
} }

View File

@ -73,8 +73,8 @@ func TestLoadMarkdownAgentsDir_ModeOrchestratorsCoexist(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
} }
write(OrchestratorMarkdownFilename, "---\nname: Deep\n---\n\ndeep\n") write(OrchestratorMarkdownFilename, "---\nname: Deep\nmax_iterations: 400\n---\n\ndeep\n")
write(OrchestratorPlanExecuteMarkdownFilename, "---\nname: PE\n---\n\npe\n") write(OrchestratorPlanExecuteMarkdownFilename, "---\nname: PE\nmax_iterations: 600\n---\n\npe\n")
write(OrchestratorSupervisorMarkdownFilename, "---\nname: SV\n---\n\nsv\n") write(OrchestratorSupervisorMarkdownFilename, "---\nname: SV\n---\n\nsv\n")
write("worker.md", "---\nid: worker\nname: Worker\n---\n\nw\n") write("worker.md", "---\nid: worker\nname: Worker\n---\n\nw\n")
@ -82,10 +82,10 @@ func TestLoadMarkdownAgentsDir_ModeOrchestratorsCoexist(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if load.Orchestrator == nil || load.Orchestrator.Instruction != "deep" { if load.Orchestrator == nil || load.Orchestrator.Instruction != "deep" || load.Orchestrator.MaxIterations != 400 {
t.Fatalf("deep: %+v", load.Orchestrator) t.Fatalf("deep: %+v", load.Orchestrator)
} }
if load.OrchestratorPlanExecute == nil || load.OrchestratorPlanExecute.Instruction != "pe" { if load.OrchestratorPlanExecute == nil || load.OrchestratorPlanExecute.Instruction != "pe" || load.OrchestratorPlanExecute.MaxIterations != 600 {
t.Fatalf("pe: %+v", load.OrchestratorPlanExecute) t.Fatalf("pe: %+v", load.OrchestratorPlanExecute)
} }
if load.OrchestratorSupervisor == nil || load.OrchestratorSupervisor.Instruction != "sv" { if load.OrchestratorSupervisor == nil || load.OrchestratorSupervisor.Instruction != "sv" {

View File

@ -130,7 +130,7 @@ type MultiAgentConfig struct {
Orchestration string `yaml:"orchestration,omitempty" json:"orchestration,omitempty"` Orchestration string `yaml:"orchestration,omitempty" json:"orchestration,omitempty"`
// MaxIteration 已废弃:统一使用 agent.max_iterations(YAML 中保留字段仅为兼容旧配置,运行时不读取)。 // MaxIteration 已废弃:统一使用 agent.max_iterations(YAML 中保留字段仅为兼容旧配置,运行时不读取)。
MaxIteration int `yaml:"max_iteration,omitempty" json:"max_iteration,omitempty"` MaxIteration int `yaml:"max_iteration,omitempty" json:"max_iteration,omitempty"`
// PlanExecuteLoopMaxIterations plan_execute 模式下 execute↔replan 外层循环上限;0 表示用 Agent 默认 10。 // PlanExecuteLoopMaxIterations plan_execute 模式下向 executor 委派的外层步数上限;0 表示不单独限制(统一受 agent.max_iterations 约束)。
PlanExecuteLoopMaxIterations int `yaml:"plan_execute_loop_max_iterations,omitempty" json:"plan_execute_loop_max_iterations,omitempty"` PlanExecuteLoopMaxIterations int `yaml:"plan_execute_loop_max_iterations,omitempty" json:"plan_execute_loop_max_iterations,omitempty"`
// SubAgentMaxIterations 已废弃:子代理与主代理均使用 agent.max_iterations(Markdown max_iterations>0 可覆盖)。 // SubAgentMaxIterations 已废弃:子代理与主代理均使用 agent.max_iterations(Markdown max_iterations>0 可覆盖)。
SubAgentMaxIterations int `yaml:"sub_agent_max_iterations,omitempty" json:"sub_agent_max_iterations,omitempty"` SubAgentMaxIterations int `yaml:"sub_agent_max_iterations,omitempty" json:"sub_agent_max_iterations,omitempty"`
@ -2358,7 +2358,7 @@ func Default() *Config {
}, },
OpenAI: OpenAIConfig{}, OpenAI: OpenAIConfig{},
Agent: AgentConfig{ Agent: AgentConfig{
MaxIterations: 30, // 默认最大迭代次数 MaxIterations: 3000, // 默认最大迭代次数(与 multiagent.defaultAgentMaxIterations 一致)
ToolTimeoutMinutes: 10, // 单次工具执行默认最多 10 分钟,避免异常长时间占用 ToolTimeoutMinutes: 10, // 单次工具执行默认最多 10 分钟,避免异常长时间占用
ToolWaitTimeoutSeconds: 60, // 外部 MCP 工具单轮最多等待 60 秒,超时后返回 execution_id 可继续等待 ToolWaitTimeoutSeconds: 60, // 外部 MCP 工具单轮最多等待 60 秒,超时后返回 execution_id 可继续等待
ExternalMCPMaxConcurrentPerServer: 2, // 单个外部 MCP server 默认最多 2 个工具同时执行 ExternalMCPMaxConcurrentPerServer: 2, // 单个外部 MCP server 默认最多 2 个工具同时执行

View File

@ -156,18 +156,21 @@ func finalizationCheckMessage(d agentfinalizer.Decision) string {
if d.Finalizable { if d.Finalizable {
return "已交付本轮回复。" return "已交付本轮回复。"
} }
if d.CompletionReason == multiagent.ReasonUnfinishedPlan { switch d.CompletionReason {
case multiagent.ReasonUnfinishedPlan:
return unfinishedPlanNotice(d.UnfinishedPlanSteps) return unfinishedPlanNotice(d.UnfinishedPlanSteps)
} case multiagent.ReasonIterationLimit, multiagent.ReasonPlanningIterationLimit:
return iterationLimitNotice(d.CompletionReason, d.UnfinishedPlanSteps)
default:
return finalizationBlockedMessage(d) return finalizationBlockedMessage(d)
}
} }
func unfinishedPlanNotice(steps []multiagent.PlanStep) string { func formatPlanStepBullets(steps []multiagent.PlanStep) string {
if len(steps) == 0 { if len(steps) == 0 {
return "本轮任务未完成,计划中仍有待执行或进行中的步骤。" return ""
} }
var notice strings.Builder var b strings.Builder
fmt.Fprintf(&notice, "本轮任务未完成,还有 %d 个计划步骤未结束。\n", len(steps))
escapeTitle := strings.NewReplacer( escapeTitle := strings.NewReplacer(
"\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "~", "\\~", "\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "~", "\\~",
"[", "\\[", "]", "\\]", "<", "\\<", ">", "\\>", "&", "\\&", "[", "\\[", "]", "\\]", "<", "\\<", ">", "\\>", "&", "\\&",
@ -181,9 +184,27 @@ func unfinishedPlanNotice(steps []multiagent.PlanStep) string {
if title == "" { if title == "" {
title = "步骤 #" + step.ID title = "步骤 #" + step.ID
} }
fmt.Fprintf(&notice, "\n- %s · %s", status, escapeTitle.Replace(title)) fmt.Fprintf(&b, "\n- %s · %s", status, escapeTitle.Replace(title))
} }
return notice.String() return b.String()
}
func unfinishedPlanNotice(steps []multiagent.PlanStep) string {
if len(steps) == 0 {
return "本轮任务未完成,计划中仍有待执行或进行中的步骤。"
}
return fmt.Sprintf("本轮任务未完成,还有 %d 个计划步骤未结束。\n%s", len(steps), formatPlanStepBullets(steps))
}
func iterationLimitNotice(reason string, steps []multiagent.PlanStep) string {
base := "本轮代理已达到最大迭代轮次上限,任务尚未完成。可发送「继续」基于已有轨迹接着执行,或在配置中调大 agent.max_iterations。"
if reason == multiagent.ReasonPlanningIterationLimit {
base = "Plan-Execute 已达到计划执行步数预算上限,任务尚未完成。可发送「继续」基于已有轨迹接着执行,或在配置中调大 multi_agent.plan_execute_loop_max_iterations(设为 0 表示不单独限制)。"
}
if len(steps) == 0 {
return base
}
return fmt.Sprintf("%s\n\n未结束的计划步骤(%d 项):\n%s", base, len(steps), formatPlanStepBullets(steps))
} }
func finalizationBlockedMessage(d agentfinalizer.Decision) string { func finalizationBlockedMessage(d agentfinalizer.Decision) string {
@ -197,6 +218,13 @@ func finalizationBlockedMessage(d agentfinalizer.Decision) string {
} }
return notice return notice
} }
if d.CompletionReason == multiagent.ReasonIterationLimit || d.CompletionReason == multiagent.ReasonPlanningIterationLimit {
notice := iterationLimitNotice(d.CompletionReason, d.UnfinishedPlanSteps)
if text := strings.TrimSpace(d.FinalText); text != "" {
return notice + "\n\n**本轮已生成的内容(阶段性结果)**\n\n" + text
}
return notice
}
notice, keepText := finalizationBlockNotice(d) notice, keepText := finalizationBlockNotice(d)
parts := make([]string, 0, 4) parts := make([]string, 0, 4)
if keepText { if keepText {

View File

@ -85,3 +85,33 @@ func TestUnfinishedPlanWithoutDraftShowsOnlyNotice(t *testing.T) {
} }
} }
} }
func TestIterationLimitPreservesDraftAndUnfinishedStepsWithoutRawBlockedCheck(t *testing.T) {
for _, reason := range []string{multiagent.ReasonIterationLimit, multiagent.ReasonPlanningIterationLimit} {
result := &multiagent.RunResult{
Response: "已确认入口服务开放 8080 端口。",
RuntimeStatus: agentfinalizer.StatusBlocked,
RuntimeCompletionReason: reason,
UnfinishedPlanSteps: []multiagent.PlanStep{
{ID: "2", Subject: "验证后台弱口令", Status: "in_progress"},
},
}
decision := agentfinalizer.FromRunResult(nil, result, agentfinalizer.Input{})
if decision.Finalizable || decision.Status != agentfinalizer.StatusBlocked || decision.CompletionReason != reason {
t.Fatalf("unexpected decision for %s: %+v", reason, decision)
}
reply := finalizationBlockedMessage(decision)
for _, want := range []string{"继续", "进行中 · 验证后台弱口令", "阶段性结果", "已确认入口服务开放 8080 端口。"} {
if !strings.Contains(reply, want) {
t.Fatalf("reason=%s reply missing %q: %q", reason, want, reply)
}
}
if strings.Contains(reply, "agent run status is blocked") {
t.Fatalf("reason=%s reply leaked raw internal check: %q", reason, reply)
}
checkMsg := finalizationCheckMessage(decision)
if strings.Contains(checkMsg, "已确认入口服务开放 8080 端口。") || !strings.Contains(checkMsg, "验证后台弱口令") {
t.Fatalf("reason=%s expected concise check message, got %q", reason, checkMsg)
}
}
}

View File

@ -834,3 +834,145 @@ func TestPiTransportFailureClassifiesTLSHandshakeReset(t *testing.T) {
t.Fatalf("expected proxied route hint, got %q", proxied) t.Fatalf("expected proxied route hint, got %q", proxied)
} }
} }
func TestPiPlanExecuteUsesAgentMaxIterationsBeyondLegacy33TurnsAnd10Steps(t *testing.T) {
cfg := piTestConfig(t)
cfg.Agent.MaxIterations = 80
cfg.MultiAgent.PlanExecuteLoopMaxIterations = 0 // default 0 must not cap at 10 steps or 33 turns
const totalSteps = 12
var mainTurns atomic.Int32
var execCalls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Tools []struct {
Function struct {
Name string `json:"name"`
} `json:"function"`
} `json:"tools"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
return
}
isMain := false
for _, tool := range body.Tools {
if tool.Function.Name == "exit" {
isMain = true
break
}
}
if !isMain {
n := execCalls.Add(1)
piReply(w, "", "", nil, fmt.Sprintf("step-%d-evidence", n))
return
}
// 12 steps * 3 main turns (in_progress -> task -> completed) + exit = 37 main turns (> 33) and 12 executor delegations (> 10).
turn := int(mainTurns.Add(1))
stepIdx := (turn - 1) / 3
phase := (turn - 1) % 3
if stepIdx < totalSteps {
todos := make([]map[string]any, 0, totalSteps)
for i := 0; i < totalSteps; i++ {
status := "pending"
if i < stepIdx {
status = "completed"
} else if i == stepIdx {
if phase == 2 {
status = "completed"
} else {
status = "in_progress"
}
}
todos = append(todos, map[string]any{
"content": fmt.Sprintf("Step %d", i+1),
"status": status,
})
}
switch phase {
case 0, 2:
piReply(w, "write_todos", fmt.Sprintf("todos-%d", turn), map[string]any{"todos": todos}, "")
case 1:
piReply(w, "task", fmt.Sprintf("task-%d", stepIdx+1), map[string]any{
"subagent_type": "executor",
"description": fmt.Sprintf("Run step %d", stepIdx+1),
}, "")
}
return
}
piReply(w, "exit", "finish", map[string]any{"final_result": "All 12 plan-execute steps verified."}, "")
}))
defer server.Close()
cfg.OpenAI.BaseURL = server.URL + "/v1"
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, mcp.NewServer(zap.NewNop()), nil, zap.NewNop(), 80)
res, err := RunMultiAgent(ctx, cfg, &cfg.MultiAgent, ag, nil, zap.NewNop(), "plan-execute-long", "", "Execute full 12-step plan.", nil, nil, nil, "", "plan_execute", nil, "")
if err != nil {
t.Fatal(err)
}
if res.RuntimeStatus != "completed" || res.Response != "All 12 plan-execute steps verified." {
t.Fatalf("expected completed 12-step plan_execute run, got %+v (mainTurns=%d execCalls=%d)", res, mainTurns.Load(), execCalls.Load())
}
if execCalls.Load() != totalSteps || mainTurns.Load() <= 33 {
t.Fatalf("unexpected call counts: mainTurns=%d execCalls=%d", mainTurns.Load(), execCalls.Load())
}
}
func TestPiPlanExecuteExplicitStepBudgetAllowsSummaryAndKeepsBlockedReason(t *testing.T) {
cfg := piTestConfig(t)
cfg.Agent.MaxIterations = 20
cfg.MultiAgent.PlanExecuteLoopMaxIterations = 1
var mainTurns atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Tools []struct {
Function struct {
Name string `json:"name"`
} `json:"function"`
} `json:"tools"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
isMain := false
for _, tool := range body.Tools {
if tool.Function.Name == "exit" {
isMain = true
break
}
}
if !isMain {
piReply(w, "", "", nil, "step-1-ok")
return
}
switch mainTurns.Add(1) {
case 1:
piReply(w, "write_todos", "plan-1", map[string]any{"todos": []map[string]any{
{"content": "Step 1", "status": "completed"},
{"content": "Step 2", "status": "in_progress"},
}}, "")
case 2:
piReply(w, "task", "task-1", map[string]any{"subagent_type": "executor", "description": "Run step 1"}, "")
case 3:
piReply(w, "task", "task-2", map[string]any{"subagent_type": "executor", "description": "Run step 2"}, "")
default:
piReply(w, "exit", "exit-partial", map[string]any{"final_result": "Completed step 1; step 2 awaits more budget."}, "")
}
}))
defer server.Close()
cfg.OpenAI.BaseURL = server.URL + "/v1"
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, mcp.NewServer(zap.NewNop()), nil, zap.NewNop(), 20)
res, err := RunMultiAgent(ctx, cfg, &cfg.MultiAgent, ag, nil, zap.NewNop(), "plan-execute-budget", "", "Run two steps.", nil, nil, nil, "", "plan_execute", nil, "")
if err != nil {
t.Fatal(err)
}
if res.RuntimeStatus != "blocked" || res.RuntimeCompletionReason != ReasonPlanningIterationLimit {
t.Fatalf("expected blocked planning_iteration_limit, got %+v", res)
}
if res.Response != "Completed step 1; step 2 awaits more budget." {
t.Fatalf("expected summary response to be preserved, got %q", res.Response)
}
if len(res.UnfinishedPlanSteps) != 1 || res.UnfinishedPlanSteps[0].Subject != "Step 2" {
t.Fatalf("expected unfinished step 2 to be retained, got %+v", res.UnfinishedPlanSteps)
}
}

View File

@ -122,13 +122,17 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
registry[id] = sub registry[id] = sub
catalog = append(catalog, id+": "+sub.Description) catalog = append(catalog, id+": "+sub.Description)
} }
instruction, _ := resolveMainOrchestratorInstruction(mode, ma, loaded) instruction, meta := resolveMainOrchestratorInstruction(mode, ma, loaded)
prompt := project.AppendSystemPromptBlock(instruction, extra) prompt := project.AppendSystemPromptBlock(instruction, extra)
prompt += "\n\nAvailable specialists:\n" + strings.Join(catalog, "\n") + "\nUse task to delegate a concrete objective. Each child receives only the tools permitted for it and this conversation. Verify evidence before reporting completion." prompt += "\n\nAvailable specialists:\n" + strings.Join(catalog, "\n") + "\nUse task to delegate a concrete objective. Each child receives only the tools permitted for it and this conversation. Verify evidence before reporting completion."
if mode == "plan_execute" { if mode == "plan_execute" {
prompt += "\nCreate a concrete plan using the available task-board tools or a concise plan in text. Delegate one step at a time to executor using task, examine the result, update the plan, and replan when evidence requires it. Finish with the verified deliverable." prompt += "\nCreate a concrete plan using the available task-board tools or a concise plan in text. Delegate one step at a time to executor using task, examine the result, update the plan, and replan when evidence requires it. Finish with the verified deliverable."
} }
main := &piRun{cfg: cfg, ag: ag, db: db, projectID: projectID, conversationID: conversationID, agentID: "main", systemPrompt: prompt, systemPromptPrefix: instruction, history: history, roleTools: roleTools, progress: progress, reasoning: intent, sessionKey: mode} var orchestratorMaxIterations int
if meta != nil {
orchestratorMaxIterations = meta.MaxIterations
}
main := &piRun{cfg: cfg, ag: ag, db: db, projectID: projectID, conversationID: conversationID, agentID: "main", systemPrompt: prompt, systemPromptPrefix: instruction, history: history, roleTools: roleTools, progress: progress, reasoning: intent, sessionKey: mode, maxTurns: resolveMaxIterations(cfg, orchestratorMaxIterations)}
str := map[string]any{"type": "string"} str := map[string]any{"type": "string"}
main.extraTools = []agentruntime.Tool{ main.extraTools = []agentruntime.Tool{
{Name: "task", Description: "Delegate a concrete task to a named specialist and return its evidence-backed result", Parameters: piToolSchema(map[string]any{"subagent_type": str, "description": str}, "subagent_type", "description")}, {Name: "task", Description: "Delegate a concrete task to a named specialist and return its evidence-backed result", Parameters: piToolSchema(map[string]any{"subagent_type": str, "description": str}, "subagent_type", "description")},
@ -142,16 +146,8 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
} }
planLimitReached := false planLimitReached := false
planCalls := 0 planCalls := 0
// plan_execute_loop_max_iterations <= 0 表示不单独限制 executor 委派步数,统一受 agent.max_iterations(及主代理 max_iterations)约束。
planLimit := ma.PlanExecuteLoopMaxIterations planLimit := ma.PlanExecuteLoopMaxIterations
if planLimit <= 0 {
planLimit = 10
}
if mode == "plan_execute" {
main.maxTurns = planLimit*3 + 3
if cap := agentMaxIterations(cfg); cap < main.maxTurns {
main.maxTurns = cap
}
}
main.extraTools = append(main.extraTools, agentruntime.Tool{Name: "exit", Description: "Finish with the verified final deliverable", Parameters: piToolSchema(map[string]any{"final_result": str}, "final_result")}) main.extraTools = append(main.extraTools, agentruntime.Tool{Name: "exit", Description: "Finish with the verified final deliverable", Parameters: piToolSchema(map[string]any{"final_result": str}, "final_result")})
if mode == "supervisor" { if mode == "supervisor" {
main.extraTools = append(main.extraTools, agentruntime.Tool{Name: "transfer_to_agent", Description: "Delegate to a named specialist", Parameters: piToolSchema(map[string]any{"agent_name": str, "description": str}, "agent_name", "description")}) main.extraTools = append(main.extraTools, agentruntime.Tool{Name: "transfer_to_agent", Description: "Delegate to a named specialist", Parameters: piToolSchema(map[string]any{"agent_name": str, "description": str}, "agent_name", "description")})
@ -178,16 +174,6 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
return agentruntime.ToolResult{Content: string(b)}, nil return agentruntime.ToolResult{Content: string(b)}, nil
} }
id, _ := call.Arguments["subagent_type"].(string) id, _ := call.Arguments["subagent_type"].(string)
if mode == "plan_execute" {
idsMu.Lock()
if planCalls >= planLimit {
planLimitReached = true
idsMu.Unlock()
return agentruntime.ToolResult{Content: "Planning step budget reached. Existing results are preserved; further execution needs a new budget.", Terminate: true}, nil
}
planCalls++
idsMu.Unlock()
}
if call.Name == "transfer_to_agent" { if call.Name == "transfer_to_agent" {
id, _ = call.Arguments["agent_name"].(string) id, _ = call.Arguments["agent_name"].(string)
} }
@ -196,6 +182,19 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
if !ok || strings.TrimSpace(task) == "" { if !ok || strings.TrimSpace(task) == "" {
return agentruntime.ToolResult{}, fmt.Errorf("unknown specialist or empty task") return agentruntime.ToolResult{}, fmt.Errorf("unknown specialist or empty task")
} }
if mode == "plan_execute" && planLimit > 0 {
idsMu.Lock()
if planCalls >= planLimit {
planLimitReached = true
idsMu.Unlock()
return agentruntime.ToolResult{
Content: fmt.Sprintf("Planning step budget (%d) reached. Stop delegating further task steps and summarize verified findings and remaining plan items via exit.", planLimit),
IsError: true,
}, nil
}
planCalls++
idsMu.Unlock()
}
tools := sub.RoleTools tools := sub.RoleTools
if sub.BindRole != "" { if sub.BindRole != "" {
role, ok := cfg.Roles[sub.BindRole] role, ok := cfg.Roles[sub.BindRole]
@ -217,14 +216,23 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
idsMu.Lock() idsMu.Lock()
childIDs = append(childIDs, res.MCPExecutionIDs...) childIDs = append(childIDs, res.MCPExecutionIDs...)
idsMu.Unlock() idsMu.Unlock()
return agentruntime.ToolResult{Content: res.Response, IsError: err != nil}, err content := res.Response
if res.Status == ReasonIterationLimit {
note := "[Sub-agent reached its max_iterations limit before finishing this step; inspect recorded tool results/facts and split remaining work if needed.]"
if strings.TrimSpace(content) == "" {
content = note
} else {
content += "\n\n" + note
}
}
return agentruntime.ToolResult{Content: content, IsError: err != nil}, err
} }
res, err := main.run(ctx, message) res, err := main.run(ctx, message)
if res != nil { if res != nil {
idsMu.Lock() idsMu.Lock()
if planLimitReached { if planLimitReached {
res.RuntimeStatus = "blocked" res.RuntimeStatus = "blocked"
res.RuntimeCompletionReason = "planning_iteration_limit" res.RuntimeCompletionReason = ReasonPlanningIterationLimit
} }
if deliverable != "" { if deliverable != "" {
res.Response = deliverable res.Response = deliverable
@ -719,7 +727,8 @@ func piResultFromRuntime(res *agentruntime.Result, ids []string, plan piRunPlan)
out.RuntimeCompletionReason = ReasonModelOutputTruncated out.RuntimeCompletionReason = ReasonModelOutputTruncated
case "iteration_limit": case "iteration_limit":
out.RuntimeStatus = "blocked" out.RuntimeStatus = "blocked"
out.RuntimeCompletionReason = "iteration_limit" out.RuntimeCompletionReason = ReasonIterationLimit
out.UnfinishedPlanSteps = plan.unfinishedSteps()
case "canceled": case "canceled":
out.RuntimeStatus = "cancelled" out.RuntimeStatus = "cancelled"
case "failed": case "failed":

View File

@ -3,6 +3,8 @@ package multiagent
const ( const (
ReasonModelOutputTruncated = "model_output_truncated" ReasonModelOutputTruncated = "model_output_truncated"
ReasonUnfinishedPlan = "unfinished_plan" ReasonUnfinishedPlan = "unfinished_plan"
ReasonIterationLimit = "iteration_limit"
ReasonPlanningIterationLimit = "planning_iteration_limit"
) )
type PlanStep struct { type PlanStep struct {