Skip to content

[Runtime] Add run budgets and runaway-agent safeguards #17

Open

Description

@helsome

Background

Deep Research / Agent 属于长链路任务,单次任务可能持续进行模型调用、搜索、检索和工具调用。如果缺少统一的运行预算与循环检测,错误规划、provider 异常或重复搜索可能造成任务长时间不结束、成本失控、重复请求和不可解释的卡死。

当前需要把“Agent 最多可以做多少事”变成明确的 runtime contract,而不是依赖每个 workflow 自己约束。

Requirements

建立统一的 Run Budget,至少支持:

  • wall-clock duration;
  • model call count;
  • tool call count;
  • search / retrieval iteration count;
  • input/output token budget(provider 可提供时);
  • estimated / actual cost budget(provider 可提供时)。

同时提供 runaway detection:

  • 连续重复相同 tool call;
  • 相同或近似相同 search query 循环;
  • 无新增 evidence / progress 的连续迭代;
  • retry storm。

运行达到预算或命中 runaway 条件时:

  • 不能直接把任务表现为普通 success;
  • 返回稳定、machine-readable 的 stop_reason;
  • 尽可能保存已有 evidence、partial report、trace 和运行状态;
  • 用户可以看见任务为何停止,以及已完成到哪里;
  • 支持合理的默认预算,并允许显式 per-run override;
  • override 仍应有系统级 hard ceiling,避免无限运行。

与 #14 对接:Langfuse trace / evaluation 中应能记录 budget、consumption、stop_reason 和 loop-detection event。

Acceptance Criteria

  • Agent / Deep Research 使用统一 budget contract,而不是各 workflow 独立 hardcode。
  • 至少能限制 duration、model calls、tool calls、search/retrieval iterations。
  • token / cost 数据可获取时纳入 budget 和 summary。
  • 对明显重复 tool/search loop 有自动检测和终止。
  • 达到 budget 后保留 partial result,并明确标识 stop_reason=budget_exhausted 或等价状态。
  • 正常任务不会因 telemetry/provider 无法提供 token/cost 数据而异常失败。
  • 有 unit/integration tests 覆盖每类 budget 与 loop detector。
  • 必须用真实 provider + production Agent path 跑一个故意设置极低 budget 的任务,确认能够真实终止;另跑一个可诱发重复搜索/工具调用的 case,确认不会无限循环。只 mock 不算验收。
  • PR 附真实运行的调用次数、耗时、stop reason 和 partial result。

Non-goals

  • 不是简单给单个 HTTP request 加 timeout。
  • 不是仅在 UI 增加“停止”按钮;重点是 runtime 自身具备可验证的硬约束。

Activity

  1. kbkb628 commented on Sep 11, 2026

    @kbkb628
    Collaborator

    你好,我想认领 #17(Run budgets & runaway-agent safeguards)。我打算按你给 #27 的那种节奏走:第一步交可评审的地基,真实 provider 的 E2E 验证放在后续 PR,不跳过你的验收要求。

    为什么我来做这条

    我平时就在做 agent runtime 的"止损"层,手上已有一套可复用的实现经验:统一的 run 预算契约(wall-clock / 调用次数 / token / cost),以及同工具同参数的重复调用硬熔断——参数规范化(键序无关)、被拦调用也计入、换参数或换工具或新会话时重置计数。所以 #17 里那四类 runaway(重复 tool、重复 query、无进展迭代、retry storm)和六类预算,大概会踩哪些坑我心里有数。

    第一步(基于当前代码,不引入行为变更)

    代码里目前没有任何 budget / stop_reason / loop 实现(我搜过 RunBudget、stopReason、maxToolCalls 均 0 命中),所以第一步是契约 + 纯函数检测器 + 单测:

    1. packages/shared/src/kernel/run-budget.ts
    2. packages/shared/src/kernel/runaway-detector.ts
      • 四类检测器均为确定性纯函数,返回 { detected, signal, evidence },可直接进 trace;
      • 重复 tool call 沿用 guards.ts 的约定:一次定义、调用点只 import,不在调用点重建。
    3. 单测覆盖每类预算与每个检测器的边界(阈值、计数重置、误报场景)。

    接线(在 RunManager 真正读预算、命中后写 stop_reason 并保留 partial result)我计划放第二步;如果你希望第一步就带最小接线(仅在 run 结果上暴露 stop_reason、不改变现有行为),我按你的偏好调整。

    真实 provider 的极低 budget E2E + 故意诱发重复检索的 case,会在第二步 PR 里附上调用次数、耗时、stop reason 和 partial result。

    拆分 OK 的话我就开工;若你更希望一次做完整条(含 E2E),我也可以,只是周期会长一些。谢谢!

  2. self-assigned this
    on Sep 11, 2026
  3. added
    claimedClaimed by a contributor and currently in progress
    on Sep 11, 2026
  4. kbkb628 commented on Sep 11, 2026

    @kbkb628
    Collaborator

    进度更新:#17 的实现已分两步提交,并且真实 provider 的 E2E 已经跑通。

    交付

    • feat(shared): add run budget contract and runaway detectors (step 1 of #17) #47(step 1/2):RunBudgetLimits / RunBudgetUsage 契约、StopReason 词表、resolveBudget(defaults ← per-run override ← 系统 ceiling,并回报被夹紧的键)、四类 runaway 检测器(重复 tool call / 近似重复 search query / 同一证据集无进展 / retry storm)。纯函数、状态可序列化,32 个单测。
    • feat(shared): enforce run budgets and runaway stops in RunManager (step 2a of #17) #49(step 2):接进 RunManager(每个 runtime 事件累加 usage 并喂检测器,命中即 runtime.cancel(),run 落成 cancelled 并保留 partial result),并在 AgentKernel 透传 budgets / searchTools / runaway;Run 记录新增 stopReason / stopDetail。附带 scripts/eval/budget-smoke.ts 作为真实 provider 的 E2E 门禁。

    真实 provider E2E(按验收要求,非 mock)

    路径:AgentKernel → RunManager → PiRuntimeAdapter → pi runtime → DeepSeek。完整 JSON 与复现命令见 #49 的评论,摘要:

    • 极低预算(--max-model-calls 1):真实调用 1 次后被中止 → status=cancelled、stop_reason=budget_exhausted、detail={key:modelCalls,limit:1,used:1},assistant partial answer 保留(84 字符)。
    • 诱发重复工具调用(--loop-threshold 2):模型连续两次发出完全相同的 bash {"command":"printf ping"} → stop_reason=loop_detected、detail={signal:repeated_tool_call,tool:bash,count:2},2 个 toolCalls 记录保留。

    两条都满足:不表现为普通 success、返回 machine-readable stop_reason、保留已有 evidence / partial result。

    一个仓库级阻塞(供参考)

    bun test --isolate 在全新 clone 上会红 7 个用例(packages/longbridge-tools 的账户 fixture 按约定不入库),因此 #47/#49 的 Unit tests 目前也是同样的 7 个失败 —— #10 正是修这个的,且它现在 3/3 checks 全绿。合并 #10 之后我会 rebase 相关 PR,让这套门禁恢复绿色。

    仍未做

    • UI 渲染 stop_reason / stop_detail(目前已持久化在 run 记录里,UI 尚未展示)
    • observeRetry 未接线:AgentEvent 词表目前没有 retry 事件(检测器已实现并有单测)

    如果预算契约的形状需要调整(例如 ceiling 从「强制夹紧」改成「非法即拒绝」),或 step 1/2 的拆分希望换一种方式,我在 #47/#49 上改。

  5. helsome commented on Sep 11, 2026

    @helsome
    OwnerAuthor

    维护进度更新

    Run Budget 的 runtime 核心接线已完成并进入 main。

    处理过程:

    最终验证(合并后 main):

    • ✅ Unit tests
    • ✅ Typecheck
    • ✅ Secret scan

    原 #49 中已有的真实 provider E2E 仍有效:低 model-call budget 可得到 budget_exhausted 并保留 partial answer;重复工具调用可得到 loop_detected 并保留 tool call 记录。

    当前 #17 尚可继续处理的缺口:

    • UI 展示 stopReason / stopDetail,让用户明确看到为什么被预算/循环保护中止;
    • observeRetry 接线(当前 AgentEvent 尚无 retry 事件,需要先定义可靠的 retry signal)。
  6. github-actions commented on Sep 21, 2026

    @github-actions

    @kbkb628 这个 Issue 已认领超过 7 天,目前没有发现关联的 open PR,也没有看到最近 7 天的进度更新。

    如果仍在推进,请在 3 天内 留一条简短进度说明(包括正在等待的前置依赖也可以);如果已经有 PR,请贴出链接。若 3 天内没有回应,认领会自动释放,方便其他贡献者接手。

  7. github-actions commented on Sep 25, 2026

    @github-actions

    @kbkb628 在提醒后 3 天内没有进度回应,且仍未发现关联的 open PR;本次认领已自动释放。Issue 保持开放,可以重新认领。

  8. 5 remaining items

  9. github-actions commented on Oct 18, 2026

    @github-actions

    @Guo-Yixin 这个 Issue 已认领超过 7 天,目前没有发现关联的 open PR,也没有看到最近 7 天的进度更新。

    如果仍在推进,请在 3 天内 留一条简短进度说明(包括正在等待的前置依赖也可以);如果已经有 PR,请贴出链接。若 3 天内没有回应,认领会自动释放,方便其他贡献者接手。

  10. removed
    claimedClaimed by a contributor and currently in progress
    on Oct 21, 2026
  11. github-actions commented on Oct 21, 2026

    @github-actions

    @Guo-Yixin 在提醒后 3 天内没有进度回应,且仍未发现关联的 open PR;本次认领已自动释放。Issue 保持开放,可以重新认领。

  12. lhy-dcf commented on Nov 20, 2026

    @lhy-dcf
    Contributor

    我来认领 #17,处理维护者在「维护进度更新」中列出的剩余缺口之二:observeRetry 接线(另一个缺口 stopReason 的 UI 展示不在本 claim 范围内)。

    范围

    1. AgentEvent 词表新增 tool_retried 事件(packages/core):可靠 retry 信号定义为「同一工具上一次执行以 error 结束后的再次执行」——纯 adapter 层推导,不依赖 Pi runtime 内部重试机制(Pi 的 error 事件直接映射为 run_failed 终态,模型层 retry 信号不可得)。
    2. PiEventAdapter 发射该事件:按 toolName 记录上次 execution_end 的错误状态,error 后再次 tool_execution_start 时在 tool_started 之后追加 tool_retried。
    3. RunManager 接线:tool_retried 事件喂给 feat(shared): add run budget contract and runaway detectors (step 1 of #17) #47 已合并的 observeRetry retry-storm 检测器,命中阈值即走既有 safeguard 流程(machine-readable stop_reason=retry_storm,保留 partial result)。不改预算算法。
    4. adapter 与 run-manager 单测覆盖:error 后重试产出事件、成功后重发不产出、阈值内不停止、命中阈值停止并保留 tool calls。

    与 #47/#54 的既有工作正交:observeToolCall(同 tool 同 args)与 observeRetry(窗口内失败重试计数)互补,分别覆盖「重复调用」与「失败重试风暴」两类 runaway。验收标准中的 retry storm 检测由此补全为真正接线(不再只是有单测的孤立检测器)。

  13. lhy-dcf commented on Nov 21, 2026

    @lhy-dcf
    Contributor

    D:/Git/claim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions