@@ -24,6 +24,11 @@ type ToolCallCallback func()
2424 // UsageCallback is called with accumulated token usage after each LLM call.
2525 type UsageCallback func(inputTokens, outputTokens int)
2626
27+// ScratchpadReader provides read access to the agent's working plan.
28+type ScratchpadReader interface {
29+ Content() string
30+}
31+
2732 // ProcessTurnOptions holds configuration for processing a turn.
2833 type ProcessTurnOptions struct {
2934 Provider provider.Provider
@@ -34,6 +39,7 @@ type ProcessTurnOptions struct {
3439 OnDelta DeltaCallback // Optional: called for each stream event
3540 OnToolCall ToolCallCallback // Optional: called before executing tool calls
3641 OnUsage UsageCallback // Optional: called with token usage after each LLM call
42+ Scratchpad ScratchpadReader // Optional: agent plan injected at context tail
3743 MaxToolRounds int
3844 }
3945
@@ -75,7 +81,7 @@ func emitAssistant(opts *ProcessTurnOptions, resp *provider.ChatResponse) {
7581 // It streams events via OnDelta and emits complete messages via OnMessage.
7682 func ProcessTurn(ctx context.Context, opts ProcessTurnOptions) error {
7783 if opts.MaxToolRounds == 0 {
78- opts.MaxToolRounds = 20
84+ opts.MaxToolRounds = 40
7985 }
8086
8187 // Convert MCP tools to provider format once
@@ -96,6 +102,13 @@ func ProcessTurn(ctx context.Context, opts ProcessTurnOptions) error {
96102 compactOldToolResults(opts.History)
97103 }
98104
105+ // Inject context recitation at the tail of the history to keep
106+ // the model focused. Two sources:
107+ // 1. Scratchpad (agent-written plan) — always injected when present.
108+ // 2. Goal reminder (user's original request) — injected every
109+ // reminderInterval rounds as a fallback when no scratchpad exists.
110+ opts.History = injectRecitation(opts.History, opts.Scratchpad, round)
111+
99112 resp, err := streamAndCollect(ctx, &opts, providerTools)
100113 if err != nil {
101114 return fmt.Errorf("LLM stream failed: %w", err)
@@ -283,6 +296,12 @@ func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provide
283296 // compacted once the LLM has already processed it.
284297 const maxToolResultLen = 200
285298
299+// reminderInterval is the number of tool-calling rounds between synthetic
300+// goal reminders. After this many rounds the loop injects a system message
301+// reciting the user's original request so it stays in the model's recent
302+// attention window.
303+const reminderInterval = 5
304+
286305 // compactOldToolResults replaces verbose tool-result messages that the LLM
287306 // has already responded to with a short summary. A tool result is considered
288307 // "processed" when an assistant message appears after it in the history.
@@ -331,6 +350,65 @@ func trimToolResult(content string) string {
331350 return content[:firstNL] + "\n[Truncated — already processed by assistant]"
332351 }
333352
353+// recitationPrefix marks synthetic recitation messages so stale ones can be
354+// removed before injecting a fresh one.
355+const recitationPrefix = "[Recitation]"
356+
357+// injectRecitation manages the tail-of-context recitation that keeps the
358+// model focused during long tool-calling loops. It removes any stale
359+// recitation message and, when appropriate, appends a fresh one.
360+//
361+// Priority: if the agent has written a scratchpad (plan/notes), that is
362+// injected on every round. Otherwise, on every reminderInterval rounds,
363+// the user's original request is echoed as a fallback.
364+func injectRecitation(history []provider.Message, pad ScratchpadReader, round int) []provider.Message {
365+ // Strip any previous recitation. Use "user" role so recitation stays
366+ // in the conversation messages and does not get hoisted into the
367+ // Anthropic system blocks (which would invalidate the prompt cache).
368+ n := 0
369+ for _, m := range history {
370+ if m.Role == "user" && strings.HasPrefix(m.Content, recitationPrefix) {
371+ continue
372+ }
373+ history[n] = m
374+ n++
375+ }
376+ history = history[:n]
377+
378+ // If the agent has a scratchpad, always inject it.
379+ if pad != nil {
380+ if plan := pad.Content(); plan != "" {
381+ return append(history, provider.Message{
382+ Role: "user",
383+ Content: recitationPrefix + " Current plan:\n" + plan,
384+ CreatedAt: time.Now(),
385+ })
386+ }
387+ }
388+
389+ // Fallback: periodic goal reminder using the user's original request.
390+ // Search forward to find the first user message (the original request),
391+ // not the last one which may be a follow-up or synthetic message.
392+ if round > 0 && round%reminderInterval == 0 {
393+ var userContent string
394+ for _, m := range history {
395+ if m.Role == "user" {
396+ userContent = m.Content
397+ break
398+ }
399+ }
400+ if userContent != "" {
401+ return append(history, provider.Message{
402+ Role: "user",
403+ Content: recitationPrefix + " The user's request: " + userContent,
404+ CreatedAt: time.Now(),
405+ })
406+ }
407+ }
408+
409+ return history
410+}
411+
334412 // extractTextFromContent extracts text from MCP content blocks.
335413 func extractTextFromContent(content []mcp.ContentBlock) string {
336414 var text string