Skip to content

Commit 4602a60

Browse files
authored
fix(agents): surface bucketed tool-loop warnings (#135103)
Carry typed admission warnings into admitted tool results after raw outcome recording, including single-call wrappers. Keep warning buckets on canonical diagnostic sessions and leave critical recovery unchanged. Preserve private result state and empty display-content normalization. Cover thresholds, outcome hashes, model context, and both batch modes.
1 parent 3bac828 commit 4602a60

12 files changed

Lines changed: 260 additions & 39 deletions

‎docs/tools/loop-detection.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,11 @@ When a loop is detected, OpenClaw logs a loop event and either warns or blocks
138138
the next tool-cycle depending on severity, protecting against runaway token
139139
spend and lockups while preserving normal tool access.
140140

141-
- Warnings come first.
141+
- Warnings come first. On OpenClaw-executed tool calls, a short system note is
142+
appended to the affected tool result so the model can change approach before
143+
a critical block. Warnings share the diagnostic log's rate limit, rather than
144+
appearing on every repeated call. The raw outcome is recorded before the note
145+
is added, so warning text does not count as progress.
142146
- Blocking follows once a pattern persists past the warning threshold.
143147
- In the embedded agent loop, the first critical loop blocks the whole tool
144148
batch before any tool in that batch runs. The model then gets one more

‎packages/agent-core/src/agent-loop.test.ts‎

Lines changed: 91 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2103,6 +2103,82 @@ describe("agentLoop tool termination", () => {
21032103
expect(events.slice(agentEnd + 1)).toEqual([]);
21042104
});
21052105

2106+
it.each(["parallel", "sequential"] as const)(
2107+
"delivers loop warnings after raw outcome hooks in %s batches",
2108+
async (toolExecution) => {
2109+
const executed: string[] = [];
2110+
const requestMessages: Message[][] = [];
2111+
const rawOutcomes: AgentToolResult<unknown>[] = [];
2112+
const streamFn = createTurnSequenceStream(
2113+
[
2114+
[
2115+
{ type: "toolCall", id: "warned", name: "read", arguments: {} },
2116+
{ type: "toolCall", id: "sibling", name: "list", arguments: {} },
2117+
],
2118+
[{ type: "toolCall", id: "next", name: "read", arguments: {} }],
2119+
[{ type: "text", text: "done" }],
2120+
],
2121+
requestMessages,
2122+
);
2123+
const events = await collectEvents(
2124+
agentLoop(
2125+
[{ role: "user", content: "run", timestamp: 1 }],
2126+
{
2127+
systemPrompt: "",
2128+
messages: [],
2129+
tools: [makeTool("read", executed), makeTool("list", executed)],
2130+
},
2131+
{
2132+
...config,
2133+
toolExecution,
2134+
beforeToolBatch: async ({ calls }) => ({
2135+
warnings: calls
2136+
.filter(({ toolCall }) => toolCall.id === "warned")
2137+
.map(({ toolCall }) => ({
2138+
kind: "tool-loop-warning" as const,
2139+
toolCallId: toolCall.id,
2140+
count: 10,
2141+
})),
2142+
}),
2143+
afterToolCall: async ({ result }) => {
2144+
rawOutcomes.push(result);
2145+
},
2146+
afterToolOutcome: async ({ result }) => {
2147+
rawOutcomes.push(result);
2148+
return { content: [...result.content, { type: "text", text: "outcome hook" }] };
2149+
},
2150+
},
2151+
undefined,
2152+
streamFn,
2153+
),
2154+
);
2155+
expect(rawOutcomes.every((result) => result.content.length === 1)).toBe(true);
2156+
const results = requestMessages.at(-1)?.filter((message) => message.role === "toolResult");
2157+
expect(results?.map((message) => message.content)).toEqual([
2158+
[
2159+
{ type: "text", text: "read result" },
2160+
{ type: "text", text: "outcome hook" },
2161+
{
2162+
type: "text",
2163+
text: "[System note: Tool-loop warning after 10 repeated calls. Change your approach or stop if you are not making progress.]",
2164+
},
2165+
],
2166+
[
2167+
{ type: "text", text: "list result" },
2168+
{ type: "text", text: "outcome hook" },
2169+
],
2170+
[
2171+
{ type: "text", text: "read result" },
2172+
{ type: "text", text: "outcome hook" },
2173+
],
2174+
]);
2175+
expect(
2176+
events.filter((event) => event.type === "tool_execution_end").map((event) => event.result),
2177+
).toEqual(results?.map((message) => expect.objectContaining({ content: message.content })));
2178+
expect(executed).toEqual(["read", "list", "read"]);
2179+
},
2180+
);
2181+
21062182
it("gives the model one recovery turn with the normal tool catalog", async () => {
21072183
const executed: string[] = [];
21082184
const providerToolNames: string[][] = [];
@@ -2622,6 +2698,9 @@ describe("agentLoop tool termination", () => {
26222698
{ systemPrompt: "", messages: [], tools: [tool] },
26232699
{
26242700
...config,
2701+
beforeToolBatch: async () => ({
2702+
warnings: [{ kind: "tool-loop-warning", toolCallId: "commit-probe", count: 10 }],
2703+
}),
26252704
afterToolCall: async () => ({ details: { phase: "after-call" } }),
26262705
afterToolOutcome: async () => ({ details: { phase: "after-outcome" } }),
26272706
},
@@ -2945,7 +3024,7 @@ describe("agentLoop tool termination", () => {
29453024
expect(events.at(-1)).toMatchObject({ type: "agent_end" });
29463025
});
29473026

2948-
it("normalizes a tool result with missing content before the next model turn", async () => {
3027+
it.each([false, true])("normalizes missing tool content with loop warning=%s", async (warn) => {
29493028
const contexts: Context[] = [];
29503029
const streamFn = createTurnSequenceStream(
29513030
[
@@ -2969,7 +3048,14 @@ describe("agentLoop tool termination", () => {
29693048
agentLoop(
29703049
[{ role: "user", content: "run", timestamp: 1 }],
29713050
{ systemPrompt: "", messages: [], tools: [tool] },
2972-
config,
3051+
{
3052+
...config,
3053+
beforeToolBatch: async () => ({
3054+
warnings: warn
3055+
? [{ kind: "tool-loop-warning", toolCallId: "call-empty", count: 10 }]
3056+
: [],
3057+
}),
3058+
},
29733059
undefined,
29743060
streamFn,
29753061
),
@@ -2980,7 +3066,9 @@ describe("agentLoop tool termination", () => {
29803066
expect.objectContaining({
29813067
role: "toolResult",
29823068
toolName: "empty",
2983-
content: [],
3069+
content: warn
3070+
? [{ type: "text", text: expect.stringContaining("Tool-loop warning after 10") }]
3071+
: [],
29843072
}),
29853073
);
29863074
});

‎packages/agent-core/src/agent-loop.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
1515
import { TranscriptNotContinuableError } from "./errors.js";
1616
import { uuidv7 } from "./harness/session/uuid.js";
1717
import {
18+
appendToolLoopWarning,
1819
copyInternalToolResultState,
1920
getInternalToolExecutionPreparer,
2021
getInternalSyncSteeringGetter,
@@ -46,6 +47,7 @@ import type {
4647
AgentToolResult,
4748
StreamFn,
4849
ToolLoopIntervention,
50+
ToolLoopWarning,
4951
} from "./types.js";
5052
import { validateToolArguments } from "./validation.js";
5153

@@ -690,6 +692,7 @@ async function executeToolCalls(
690692
});
691693
}
692694
batch.lifecycle = admission ? takeInternalToolBatchLifecycle(admission) : undefined;
695+
batch.warnings = admission?.warnings;
693696
}
694697
}
695698
let hasSequentialToolCall = false;
@@ -729,6 +732,7 @@ type ToolBatchContext = {
729732
resolved: Map<AgentToolCall, ResolvedToolCallOutcome>;
730733
validated: Map<AgentToolCall, ValidatedToolCallOutcome>;
731734
lifecycle?: InternalToolBatchLifecycle;
735+
warnings?: ToolLoopWarning[];
732736
};
733737

734738
type ResolvedToolCallOutcome =
@@ -1636,6 +1640,16 @@ async function finalizeToolCallOutcome(
16361640
batch: ToolBatchContext,
16371641
finalized: FinalizedToolCallOutcome,
16381642
args: unknown,
1643+
): Promise<FinalizedToolCallOutcome> {
1644+
const outcome = await applyToolOutcomeHook(batch, finalized, args);
1645+
const warning = batch.warnings?.find((entry) => entry.toolCallId === outcome.toolCall.id);
1646+
return warning ? { ...outcome, result: appendToolLoopWarning(outcome.result, warning) } : outcome;
1647+
}
1648+
1649+
async function applyToolOutcomeHook(
1650+
batch: ToolBatchContext,
1651+
finalized: FinalizedToolCallOutcome,
1652+
args: unknown,
16391653
): Promise<FinalizedToolCallOutcome> {
16401654
if (!batch.config.afterToolOutcome) {
16411655
return finalized;

‎packages/agent-core/src/internal-hooks.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type {
55
AgentToolUpdateCallback,
66
InternalBeforeToolBatchContext,
77
InternalBeforeToolBatchResult,
8+
ToolLoopWarning,
89
} from "./types.js";
910

1011
export type InternalBeforeToolBatchHook = (
@@ -170,6 +171,24 @@ export function copyInternalToolResultState<T extends object>(source: object, ta
170171
return target;
171172
}
172173

174+
/** Call only after raw outcome recording: feedback must not change no-progress hashes. */
175+
export function appendToolLoopWarning<T extends AgentToolResult<unknown>>(
176+
result: T,
177+
warning: ToolLoopWarning,
178+
): T {
179+
return copyInternalToolResultState(result, {
180+
...result,
181+
content: [
182+
// Match transcript normalization for tools that omit display content.
183+
...(result.content ?? []),
184+
{
185+
type: "text",
186+
text: `[System note: Tool-loop warning after ${warning.count} repeated calls. Change your approach or stop if you are not making progress.]`,
187+
},
188+
],
189+
});
190+
}
191+
173192
/** Commit one tool result after its owning message has attached. */
174193
export function acknowledgeInternalToolResult(value: object): void {
175194
const acknowledge = toolResultAcknowledgementByValue.get(value);

‎packages/agent-core/src/types.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ export interface ToolLoopIntervention {
7575
reason: string;
7676
}
7777

78+
/** Bucketed feedback for an admitted call, not a veto or recovery attempt. */
79+
export interface ToolLoopWarning {
80+
kind: "tool-loop-warning";
81+
toolCallId: string;
82+
count: number;
83+
}
84+
7885
/** Context for OpenClaw-owned whole-batch tool admission. */
7986
export interface InternalBeforeToolBatchContext {
8087
assistantMessage: AssistantMessage;
@@ -83,9 +90,9 @@ export interface InternalBeforeToolBatchContext {
8390
}
8491

8592
/** Result of OpenClaw-owned whole-batch tool admission. */
86-
export interface InternalBeforeToolBatchResult {
87-
intervention?: ToolLoopIntervention;
88-
}
93+
export type InternalBeforeToolBatchResult =
94+
| { intervention: ToolLoopIntervention; warnings?: never }
95+
| { intervention?: never; warnings?: ToolLoopWarning[] };
8996

9097
export interface DeferredToolCallContext {
9198
/** The assistant message that requested the deferred tool call. */

‎src/agents/agent-tools.before-tool-call.e2e.test.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1017,19 +1017,41 @@ describe("before_tool_call loop detection behavior", () => {
10171017
await expectUnblockedToolExecution(secondRunTool, "new-run-0", params);
10181018
});
10191019

1020-
it("escalates generic repeat diagnostics from warning to critical", async () => {
1020+
it.each(["success", "error"])("warns on repeated %s results before blocking", async (status) => {
10211021
await withToolLoopEvents(async (emitted) => {
1022-
const { tool, params } = createGenericReadRepeatFixture();
1022+
const { tool, params, execute } = createGenericReadRepeatFixture();
1023+
const rawResult = {
1024+
content: [{ type: "text", text: "same output" }],
1025+
details: { status },
1026+
};
1027+
execute.mockResolvedValue(rawResult);
10231028

10241029
for (let i = 0; i < 21; i += 1) {
1025-
await tool.execute(`read-bucket-${i}`, params, undefined, undefined);
1030+
const result = await tool.execute(`read-bucket-${i}`, params, undefined, undefined);
1031+
if (i === 20) {
1032+
expectToolLoopBlockedResult(result, "identical outcomes");
1033+
} else {
1034+
expect(result.content).toEqual([
1035+
...rawResult.content,
1036+
...(i === 10
1037+
? [{ type: "text", text: expect.stringMatching(/\[.*10.*change.*stop.*\]/i) }]
1038+
: []),
1039+
]);
1040+
expect(result.details).toEqual(rawResult.details);
1041+
}
10261042
}
10271043

10281044
const genericEvents = emitted.filter((evt) => evt.detector === "generic_repeat");
10291045
expect(genericEvents.map((evt) => [evt.level, evt.count])).toEqual([
10301046
["warning", 10],
10311047
["critical", 20],
10321048
]);
1049+
expect(execute).toHaveBeenCalledTimes(20);
1050+
expect(rawResult.content).toEqual([{ type: "text", text: "same output" }]);
1051+
const outcomes = getDiagnosticSessionState({ sessionKey: "main" }).toolCallHistory;
1052+
const resultHashes = outcomes?.flatMap((outcome) => outcome.resultHash ?? []);
1053+
expect(resultHashes).toHaveLength(20);
1054+
expect(new Set(resultHashes).size).toBe(1);
10331055
});
10341056
});
10351057

‎src/agents/agent-tools.before-tool-call.policy.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* trusted policies, approvals, normal hooks, and final owner approval must
66
* remain in this sequence.
77
*/
8+
import type { ToolLoopWarning } from "@openclaw/agent-core";
89
import { freezeDiagnosticTraceContext } from "../infra/diagnostic-trace-context.js";
910
import { getGlobalHookRunnerRegistry } from "../plugins/hook-runner-global-state.js";
1011
import { getGlobalHookRunner } from "../plugins/hook-runner-global.js";
@@ -108,6 +109,13 @@ export async function runBeforeToolCallHook(args: {
108109
}): Promise<HookOutcome> {
109110
const toolName = normalizeToolPolicyName(args.toolName || "tool");
110111
const params = args.params;
112+
let loopWarning: ToolLoopWarning | undefined;
113+
const withLoopWarning = (outcome: HookOutcome): HookOutcome => {
114+
if (!outcome.blocked && loopWarning) {
115+
outcome.loopWarning = loopWarning;
116+
}
117+
return outcome;
118+
};
111119
let releaseArgumentChurnPolicyWait: (() => void) | undefined;
112120

113121
try {
@@ -141,7 +149,7 @@ export async function runBeforeToolCallHook(args: {
141149
{ toolName, params, toolCallId: args.toolCallId },
142150
args.ctx,
143151
);
144-
if (intervention) {
152+
if (intervention?.kind === "critical-tool-loop") {
145153
const outcome: HookOutcome = {
146154
blocked: true,
147155
kind: "veto",
@@ -152,6 +160,7 @@ export async function runBeforeToolCallHook(args: {
152160
markPrivateDecision(outcome, "genericDecision");
153161
return outcome;
154162
}
163+
loopWarning = intervention;
155164
}
156165
}
157166

@@ -185,7 +194,7 @@ export async function runBeforeToolCallHook(args: {
185194
};
186195
}
187196
if (!initialCorePolicyResult && !shouldRunTrustedPolicies && !hasBeforeToolCallHooks) {
188-
return { blocked: false, params };
197+
return withLoopWarning({ blocked: false, params });
189198
}
190199
const deriveOptions =
191200
args.ctx?.cwd || args.ctx?.sandbox
@@ -291,7 +300,7 @@ export async function runBeforeToolCallHook(args: {
291300
return approvalOutcome;
292301
}
293302
if (approvalOutcome.deferredApproval) {
294-
return approvalOutcome;
303+
return withLoopWarning(approvalOutcome);
295304
}
296305
trustedApprovalParams = approvalOutcome.params;
297306
trustedApprovalResolution = approvalOutcome.approvalResolution;
@@ -318,7 +327,7 @@ export async function runBeforeToolCallHook(args: {
318327
signal: args.signal,
319328
});
320329
if (finalApprovalOutcome) {
321-
return finalApprovalOutcome;
330+
return withLoopWarning(finalApprovalOutcome);
322331
}
323332
const allowed: HookOutcome = {
324333
blocked: false as const,
@@ -328,7 +337,7 @@ export async function runBeforeToolCallHook(args: {
328337
markPrivateDecision(allowed, "ownerDecision");
329338
allowed.approvalResolution = trustedApprovalResolution;
330339
}
331-
return allowed;
340+
return withLoopWarning(allowed);
332341
}
333342
const hookEventParams = isPlainObject(policyAdjustedParams) ? policyAdjustedParams : {};
334343
const callerIdentity = getGatewayToolCallerIdentity();
@@ -385,7 +394,7 @@ export async function runBeforeToolCallHook(args: {
385394
return approvalOutcome;
386395
}
387396
if (approvalOutcome.deferredApproval) {
388-
return approvalOutcome;
397+
return withLoopWarning(approvalOutcome);
389398
}
390399
finalParams = approvalOutcome.params;
391400
finalApprovalResolution = approvalOutcome.approvalResolution ?? finalApprovalResolution;
@@ -409,7 +418,7 @@ export async function runBeforeToolCallHook(args: {
409418
signal: args.signal,
410419
});
411420
if (finalApprovalOutcome) {
412-
return finalApprovalOutcome;
421+
return withLoopWarning(finalApprovalOutcome);
413422
}
414423
const allowed: HookOutcome = {
415424
blocked: false as const,
@@ -421,7 +430,7 @@ export async function runBeforeToolCallHook(args: {
421430
if (finalApprovalResolution) {
422431
allowed.approvalResolution = finalApprovalResolution;
423432
}
424-
return allowed;
433+
return withLoopWarning(allowed);
425434
} catch (err) {
426435
const toolCallId = args.toolCallId ? ` toolCallId=${args.toolCallId}` : "";
427436
const cause = unwrapErrorCause(err);

0 commit comments

Comments
 (0)