"""FrontierAgent adapter for AgentCore's shared agent-loop engine. The ReAct loop itself lives in :mod:`agent_core.runtime.loop.agent_loop`. This module only injects the product runtime decisions through :class:`AgentLoopHooks`: sticky-session binding, the execution scope, the wall deadline, spill-file detection, and the tool execution policies. """
一个判断标准:哪些能力该做成 observer,哪些该写进 prompt(Less is More 的可操作版本)
一、项目定位:一个为”长时程复杂工作”设计的 Harness
1.1 它解决什么问题
FrontierAgent 的配套技术报告《Apodex 1.1: Scaling Agentic Intelligence for Complex Work》(arXiv:2608.23283)给了一个清晰的问题定义:
General-purpose language models can reason and synthesize knowledge, but complex work also requires sustained interaction with files, information sources, and executable code, together with state maintenance, failure recovery, and verifiable delivery. We call this working capability.
关键词是 working capability(工作能力)——不是”答对一道题”,而是”在一段真实的时间里,持续、可验证地朝一个目标推进”。
论文把这项能力拆成两条独立的扩展轴:
维度
含义
Harness 侧对应
Environment Scaling
可执行的文件 / 搜索 / 代码环境的多样性与可验证性
Sandbox(/inputs/workspace/outputs)
Agentic Coordination Scaling
分解长时程任务、并行委派、整合异步结果、重新规划
AgentBus + Task Board + Agent Team workflow
中间那条线是论文的原话:”A shared execution harness and AgentOS maintain task state and provenance across tools and agents.”
graph LR
subgraph "🔁 一轮 turn 的内部时序"
A["📥 on_loop_start"]
B["🤖 on_llm_attempt"]
C["📡 on_llm_delta"]
D["💬 on_llm_response<br/>⭐ 可回滚"]
E["🔌 on_tool_call<br/>⭐ 可批准/中断"]
F["📤 on_tool_result<br/>⭐ 可改写"]
G["🔚 on_turn_end<br/>⭐ 可提醒/停止"]
end
H["🧹 on_loop_end"]
I["🚫 on_loop_cancelled"]
A --> B --> C --> D --> E --> F --> G --> H
G -.->|"取消"| I
D -.->|"pop_last_message"| D
E -.->|"block"| E
F -.->|"replace result"| F
G -.->|"stop / inject"| G
style A fill:#C7CEEA,stroke:#9FA8DA,color:#333
style B fill:#F5F5F5,stroke:#BDBDBD,color:#333
style C fill:#F5F5F5,stroke:#BDBDBD,color:#333
style D fill:#FFB3C6,stroke:#F48FB1,color:#333
style E fill:#FFB3C6,stroke:#F48FB1,color:#333
style F fill:#FFB3C6,stroke:#F48FB1,color:#333
style G fill:#FFB3C6,stroke:#F48FB1,color:#333
style H fill:#B5EAD7,stroke:#80CBC4,color:#333
style I fill:#FFDAB9,stroke:#FFAB76,color:#333
文档里还有一条容易被忽略但极重要的规则:
Observer failures are handled according to the loop contract; cleanup and telemetry should remain best-effort, while authorization observers must fail closed.
Measured on a 200-question deep-research benchmark, the losing trials averaged ~37 duplicate web_search queries each and ran 58-122 turns where a healthy trial finishes in ~22: the identical results pile up in history, inflate the context, and steer the model into a longer wandering loop.
37 次重复搜索、58-122 轮 vs 健康 trial 的 22 轮。 这是”模型看不见的历史”造成浪费的量化证据。
classDuplicateQueryRollbackObserver(BaseObserver): """Roll back a turn whose search request was already executed. ``critical`` so the loop awaits the hook and collects the returned ``Intervention`` — a non-critical observer's return value is dropped. """
asyncdefon_llm_response(self, ctx: TurnContext) -> Intervention | None: ifnot ctx.tool_calls: # A think-only / bare-text turn is not a rollback candidate; # refresh the budget so the next tracked turn starts clean. self._consecutive_rollbacks = 0 returnNone
turn_keys: list[str] = [] for tool_call in ctx.tool_calls: ifstr(tool_call.get("name") or"") notinself._tool_names: continue key = _dedup_key(tool_call) if key: turn_keys.append(key)
ifnot turn_keys: # Untracked tools only (web_fetch / bash / …). Leave the # counter alone and let the next tracked turn manage it. returnNone
ifany( str(tool_call.get("name") or"") inself._terminal_tools for tool_call in ctx.tool_calls ): # Never pop a turn that is trying to finish — the terminal call # would be discarded with the duplicate and never re-run. logger.info( "DuplicateQueryRollback turn=%d: batch carries a terminal " "tool; letting it through without dedup bookkeeping.", ctx.turn, ) returnNone
duplicates = [key for key in turn_keys ifself._seen.get(key, 0) > 0]
Key granularity — batch, not per-query.web_search accepts a list of queries, and the whole call is one dedup unit: [a, b] and [a, c] are different searches, so a model refining a batch incrementally is never rolled back. Keying on individual queries instead fires an order of magnitude more often and pops legitimate query evolution.
“order of magnitude more often” —— 作者用了量级词,说明这个选择不是审美,是实测。
细节 3:失败的搜索不记账
1 2 3 4 5 6 7 8 9 10 11 12 13
asyncdefon_tool_result(self, ctx, result) -> ToolResult | None: """Remember a tracked request once it returned usable content.""" if _is_failed_search(result): logger.info( "DuplicateQueryRollback: %s returned no usable content; not " "recording it, so a retry is allowed.", result.name, ) returnNone key = _dedup_key({"name": result.name, "args": result.args}) if key: self._seen[key] = self._seen.get(key, 0) + 1 returnNone
def_coerce_str_list(value: Any) -> Any: """Parse a JSON-list string into a list; pass everything else through. Deliberately mirrors ``plugins.tools._coerce.coerce_json_list`` instead of importing it: nothing under ``frontier_agent/`` imports from ``plugins/``, and this observer is not the place to open that direction. The behaviour has to match, because the search tool runs the same coercion on its own ``q`` — models emit the SAME logical batch both as a real array and as a stringified one, and a key that does not coerce would file the two forms under different keys and miss the duplicate. """
这段注释信息量极大:
模型会把同一批 query 写成真 list 或 JSON 字符串——两种形式必须归一化,否则同一批查询被登记成两个 key,去重彻底失效
# Extracts the ``agent="…"`` name from every ``<report agent="…">`` block # in a collect_reports result. A name other than the orchestrator means a # sub-agent actually delivered a report (real progress); an orchestrator-only # result is a status-only notice (no_work_queued / all_collected). _REPORT_AGENT_RE = re.compile(r'<report\s+agent="([^"]*)"')
# Session-churn tools. A turn calling ONLY these does no first-hand work — # it just manages the sub-agent roster. Board tools (add_task / update_task), # data-gathering tools, and finalize_answer are deliberately excluded: they # represent progress and reset the streak. _MGMT_TOOLS = frozenset({ "create_subagent", "assign_task", "collect_reports", "stop_subagent", })
# Trivial task prompts a wind-down spin assigns to throwaway agents. Used # only to ACCELERATE the hard stop (strong signal the agent is not doing # real work), never as the sole trigger. _DEGENERATE_PROMPTS = frozenset({ "end", "done", "complete", "completed", "final", "finalize", "finish", "finished", "x", "ok", "okay", "stop", "confirm", "nothing", "na", "n/a", })
模型在”收尾幻觉”里会给 sub-agent 派发 "End."、"OK" 这种无意义任务,然后立刻”收到报告”。检测出退化分配会加速硬熔断,但退化分配本身不能单独触发熔断——注释里明写 “never as the sole trigger”。
这个”辅助信号不能单独触发”的模式,在 Harness 里非常值得抄。
3.5 AgentBus:非阻塞的 sub-agent 调度
graph TB
M["🧠 协调者<br/>main_agent"]
subgraph "📋 Task Board"
TB["📌 pending / active<br/>completed / blocked"]
end
subgraph "🚌 AgentBus"
Q["📥 非阻塞任务队列<br/>submit_task_to_session"]
F["🌾 fan-in 收割<br/>wait_any_session<br/>FIRST_COMPLETED"]
end
S1["🤖 sub-agent A<br/>session"]
S2["🤖 sub-agent B<br/>session"]
S3["🤖 sub-agent C<br/>session"]
GUARD["👁️ NoProgressGuard<br/>空转检测"]
GUARD2["👁️ AutoFanInObserver<br/>结果注入"]
M -->|"create_subagent"| S1
M -->|"assign_task<br/>(入队即返回)"| Q
M <--> TB
Q --> S1
Q --> S2
Q --> S3
S1 --> F
S2 --> F
S3 --> F
F -->|"inject_messages"| GUARD2
GUARD2 --> M
GUARD -.->|"连续空转<br/>streak ≥ 阈值"| M
M --> GUARD
style M fill:#C7CEEA,stroke:#9FA8DA,color:#333
style TB fill:#FFF9C4,stroke:#F9A825,color:#333
style Q fill:#FFDAB9,stroke:#FFAB76,color:#333
style F fill:#FFDAB9,stroke:#FFAB76,color:#333
style S1 fill:#E8D5F5,stroke:#CE93D8,color:#333
style S2 fill:#E8D5F5,stroke:#CE93D8,color:#333
style S3 fill:#E8D5F5,stroke:#CE93D8,color:#333
style GUARD fill:#FFB3C6,stroke:#F48FB1,color:#333
style GUARD2 fill:#FFB3C6,stroke:#F48FB1,color:#333
# Actual concurrency is bounded by SpawnGuard(max_parallel). # Raise via FRONTIER_AGENT_MAX_TASKS_PER_DISPATCH. MAX_TASKS_PER_DISPATCH: int = int( os.environ.get("FRONTIER_AGENT_MAX_TASKS_PER_DISPATCH", "20") )
# Hard cap on tasks per session. Past ~5 reuses the message history is # dominated by stale tool stubs and earlier conclusions, and the agent # starts anchoring on a prior (often wrong) answer instead of doing fresh # work — heavily-reused sessions score far below fresh ones. The limit # forces the main agent to spawn a new specialist instead of poisoning a # saturated session. MAX_TASKS_PER_SESSION = 5
“heavily-reused sessions score far below fresh ones”(重度复用的 session 得分远低于全新 session)。
@tool defassign_task(...): """Tool: assign_task — non-blocking task dispatch to persistent sub-agents. Wraps AgentBus.submit_task_to_session. Each call queues a task on a previously-created session; the task runs in the background. Use ``collect_reports`` to fetch results (FIRST_COMPLETED semantics). """
def_normalise_q(value: Any) -> str | None: """把 q 参数渲染成一个稳定的字符串,空则返回 None。""" coerced = _coerce_str_list(value) ifisinstance(coerced, str): stripped = coerced.strip() return stripped orNone ifisinstance(coerced, list): parts = [i.strip() for i in coerced ifisinstance(i, str) and i.strip()] return"|".join(parts) if parts elseNone returnNone
def_is_failed_search(result: ToolResult) -> bool: if result.is_error: returnTrue text = (result.result or"").strip() ifnot text or text in _FAILED_RESULT_EXACT: returnTrue return text.startswith(_FAILED_RESULT_PREFIXES)
def_dedup_key(tool_call: dict[str, Any]) -> str | None: """为一个工具调用构造去重 key;无法追踪则返回 None。 契约:no-raise —— 这条路径在关键链路上,抛异常的代价是丢掉当前这一轮。 没有可用 q 的调用按"不可追踪"处理,而不是拿剩下的参数(比如 locale)当 key, 否则会把毫不相关的查询折叠成一个。 """ name = str(tool_call.get("name") or"") ifnot name: returnNone args = tool_call.get("args") ifnotisinstance(args, dict): returnNone q = _normalise_q(args.get("q")) if q isNone: returnNone rest = { k: v for k, v in args.items() if k != "q"and k notin _COUNT_ARG_KEYS and v isnotNone } try: suffix = json.dumps(rest, sort_keys=True, default=str) except (TypeError, ValueError): suffix = repr(sorted(rest)) returnf"{name}_{q}_{suffix}"
turn_keys: list[str] = [] for tc in ctx.tool_calls: ifstr(tc.get("name") or"") notinself._tool_names: continue k = _dedup_key(tc) if k: turn_keys.append(k)
if name == "collect_reports": # 只有 orchestrator 自己的报告 = 状态通知,没有真实产出 agents = set(_REPORT_AGENT_RE.findall(text)) self._report_agents_this_turn = agents real = {a for a in agents if a != "orchestrator"} if real: # 真的有 sub-agent 交回了报告 —— 本轮有进展 self._mgmt_turn_has_work = True self._mgmt_streak = 0 self._creates_in_streak = 0 returnNone
if name == "assign_task": prompt = str(args.get("prompt") or args.get("task") or"") agent = str(args.get("agent") or"") if agent andself._prompt_is_degenerate(prompt): self._degenerate_assignment_agents.add(agent) self._mgmt_turn_has_work = False# 分配任务不等于第一手产出 returnNone
if name == "create_subagent": self._creates_in_streak += 1 self._mgmt_turn_has_work = False returnNone
if name in _MGMT_TOOLS: self._mgmt_turn_has_work = False# 管理动作不算第一手产出 else: # 有第一手工作 —— 本轮算作有进展 self._mgmt_turn_has_work = True returnNone
asyncdef_notify_loop_start(self) -> None: # observer 只需实现自己关心的回调 —— 缺失的回调直接跳过 for ob inself.observers: cb = getattr(ob, "on_loop_start", None) if cb isnotNone: await cb(self.config)
asyncdef_notify_llm_response(self, ctx: TurnContext) -> list[Intervention]: out = [] for ob inself.observers: ifnotgetattr(ob, "critical", False): continue cb = getattr(ob, "on_llm_response", None) if cb isNone: continue iv = await cb(ctx) if iv isnotNone: out.append(iv) return out
asyncdef_notify_tool_result(self, ctx: TurnContext, result: ToolResult) -> None: for ob inself.observers: cb = getattr(ob, "on_tool_result", None) if cb isNone: continue await cb(ctx, result)
asyncdef_notify_turn_end(self, ctx: TurnContext) -> list[Intervention]: out = [] for ob inself.observers: ifnotgetattr(ob, "critical", False): continue cb = getattr(ob, "on_turn_end", None) if cb isNone: continue iv = await cb(ctx) if iv isnotNone: out.append(iv) return out
这是 FrontierAgent 用一个 if 换来的教训:弹出整条 assistant 消息 = 这一批所有工具调用一起死。如果批次里有 submit_report,它永远不会重跑。
必须像真实源码那样,把”这批里有没有终结工具”作为放行条件。
坑 3:在放行时记账,而不是在结果返回时
失败的工具调用必须允许重试。记账点错了,去重就变成了”永久堵死”。
坑 4:连续回滚预算的下限是 2,不是 1
1 2 3
# 2 is the floor: 1 would mean "never roll back" (the budget check # is ``< max - 1``), which silently disables the observer. self._max_consecutive_rollbacks = max(2, int(max_consecutive_rollbacks))
Deliberately mirrors plugins.tools._coerce.coerce_json_list instead of importing it: nothing under frontier_agent/ imports from plugins/, and this observer is not the place to open that direction. The behaviour has to match, because the search tool runs the same coercion on its own q.