-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.go
More file actions
1473 lines (1345 loc) · 56.4 KB
/
Copy pathloop.go
File metadata and controls
1473 lines (1345 loc) · 56.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package loop implements the ReAct (Reasoning + Acting) agent loop.
package loop
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/BackendStack21/odek/internal/danger"
"github.com/BackendStack21/odek/internal/llm"
"github.com/BackendStack21/odek/internal/narrate"
"github.com/BackendStack21/odek/internal/redact"
"github.com/BackendStack21/odek/internal/render"
"github.com/BackendStack21/odek/internal/tool"
)
// ingestRecorderKey is the context key used to carry the per-run audit
// ingest recorder through the agent loop to tool implementations.
type ingestRecorderKey struct{}
// newToolResultNonce returns a short random hex string used to make each tool
// result delimiter unique. A per-call nonce prevents a tool (or MCP server)
// from forging the closing delimiter and injecting instructions after its own
// output.
func newToolResultNonce() string {
b := make([]byte, 8)
if _, err := rand.Read(b); err != nil {
// crypto/rand.Read only fails on platforms with no entropy source;
// fall back to a timestamp-based token rather than panicking.
return fmt.Sprintf("%x", time.Now().UnixNano())[:16]
}
return hex.EncodeToString(b)
}
// WithIngestRecorder returns a context that carries fn as the active ingest
// recorder. Callers such as cmd/odek wrapUntrusted use IngestRecorderFrom to
// read it back. Using a context value removes the package-global recorder that
// previously caused cross-session races in the WebUI.
func WithIngestRecorder(ctx context.Context, fn func(source, content string)) context.Context {
return context.WithValue(ctx, ingestRecorderKey{}, fn)
}
// IngestRecorderFrom extracts the ingest recorder from ctx, if any.
func IngestRecorderFrom(ctx context.Context) func(source, content string) {
if ctx == nil {
return nil
}
fn, _ := ctx.Value(ingestRecorderKey{}).(func(source, content string))
return fn
}
// SkillLoader is an optional callback that the loop engine calls before each
// LLM invocation to discover contextually relevant skills. The callback
// receives the latest user input and returns additional system context
// (formatted skill content) to inject, or empty string if no skills match.
type SkillLoader func(userInput string) string
// EpisodeContextFunc is an optional callback that the loop engine calls
// before each LLM invocation to discover relevant past session episodes.
// The callback receives the latest user input as a search query and returns
// formatted episode context to inject, or empty string if nothing matches.
type EpisodeContextFunc func(userInput string) string
// ExtendedMemoryContextFunc is an optional callback that returns formatted
// Extended Memory context for the latest user input. It is injected as a
// system message after the legacy memory prompt block.
type ExtendedMemoryContextFunc func(ctx context.Context, userInput string) string
// UserMessageHandler is an optional callback invoked once per new user
// message. It is used by callers (e.g. odek.New) to trigger Extended Memory
// atom extraction.
type UserMessageHandler func(ctx context.Context, msg string)
// ToolEventHandler is an optional callback invoked for each tool execution
// during the agent loop — fires before (tool_call) and after (tool_result)
// each tool invocation. Used by the WebUI for live streaming of tool events.
type ToolEventHandler func(event string, name string, data string)
// IterationInfo holds data about a single agent loop iteration, passed to
// the IterationCallback after each turn. Used for progress reporting.
type IterationInfo struct {
Turn int // current iteration (1-indexed)
MaxTurns int // max iterations configured
ToolNames []string // tools called this turn (duplicates possible)
InputTokens int // cumulative input tokens
OutputTokens int // cumulative output tokens
CacheCreationTokens int // cumulative cache creation tokens
CacheReadTokens int // cumulative cache read tokens
CachedTokens int // cumulative cached tokens (OpenAI)
TotalLatency time.Duration // cumulative wall time
HasFinalAnswer bool // true when the agent reached a final answer
ReasoningContent string // LLM reasoning before tool calls (empty if none)
IsPreTool bool // true when fired BEFORE tool execution (shows reasoning + tools)
}
// IterationCallback is an optional callback invoked after each iteration
// of the agent loop. Used by Telegram/WebUI for progress reporting.
type IterationCallback func(info IterationInfo)
// Engine runs the agent loop: observe → think → act → repeat.
type Engine struct {
client *llm.Client
registry *tool.Registry
renderer *render.Renderer // optional: colored terminal output
maxIter int
system string
baseSystem string // original system message without memory/skills
maxContext int // max context tokens (0 = no limit)
skillLoader SkillLoader // optional: loads matching skills
lastSkillMsg string // last user message that triggered skill loading (dedup)
lastEpiMsg string // last user message that triggered episode search (dedup)
lastExtMsg string // last user message that triggered extended memory search (dedup)
lastUserMsg string // last user message passed to userMsgHandler (dedup)
skillVerbose bool // show full skill banners (default: condensed)
episodeCtx EpisodeContextFunc // optional: per-turn episode search
extendedCtx ExtendedMemoryContextFunc // optional: per-turn extended memory search
userMsgHandler UserMessageHandler // optional: called once per new user message
wrapUntrusted func(source, content string) string // optional: wraps skill/episode content
toolEventHandler ToolEventHandler // optional: fires during tool execution
signalHandler SignalHandler // optional: fires on internal loop signals
// interactionMode controls how progress is surfaced to the user.
// "engaging" (default), "verbose", "enhance", or "off" (silent).
// When "off", all per-iteration render output is suppressed.
interactionMode string
// narrator produces engaging, human-friendly progress messages
// instead of raw tool call output. nil = verbose mode (default).
narrator *narrate.Narrator
// iterationCallback is an optional callback fired after each iteration.
iterationCallback IterationCallback
// memoryPromptFunc is called before each LLM invocation to get fresh
// memory content. This ensures memory mutations during a session
// are visible to the agent on the next turn.
memoryPromptFunc func() string
// memMsgIdx tracks the position of the volatile memory system message
// in the messages array. -1 means not yet inserted. Using a separate
// message for memory (rather than concatenating into messages[0]) lets
// DeepSeek/Anthropic prompt caching keep the stable baseSystem cached
// across turns — only the memory message changes each iteration.
memMsgIdx int
// PromptCaching enables Anthropic/OpenAI/DeepSeek prompt caching markers.
// When enabled, the system prompt and first user message are annotated
// with cache_control markers, and the system prompt is moved to the
// dedicated "system" field for Anthropic compatibility.
PromptCaching bool
// MaxToolParallel controls how many tool calls run concurrently per
// iteration. 0 = use default (4). Models that support parallel tool
// calling (Claude 3.5+, GPT-4o, DeepSeek V4) can emit multiple tool
// calls in one response — this setting bounds concurrency so tools
// like read_file, search_files, and web_search run in parallel while
// avoiding resource exhaustion.
MaxToolParallel int
// maxConsecutiveToolErrors tracks how many consecutive error results
// each tool has produced. Reset on success, incremented on error.
// When a tool hits 3 consecutive errors, the loop injects a corrective
// system message suggesting alternative tools instead of letting the
// LLM keep retrying the same failing tool.
maxConsecutiveToolErrors map[string]int
// approver gates dangerous operations. When set and the LLM returns
// multiple tool calls in one iteration, a single batch approval prompt
// is shown before any tool executes, but ONLY for tools whose risk
// class requires approval according to dangerousCfg. If the batch is
// denied, no tools run for that iteration. If approved, SetTrustAll(true)
// is called on the approver (if supported) so individual tool-level
// PromptCommand calls auto-approve.
approver danger.Approver
dangerousCfg *danger.DangerousConfig // used by batch gate to pre-check risk
// Token accounting — accumulated across all iterations of the most recent run.
// Reset on each Run/RunWithMessages call and read by callers (e.g. WebUI).
TotalInputTokens int
TotalOutputTokens int
// Cache metrics accumulated across all iterations.
TotalCacheCreationTokens int // Anthropic: tokens written to cache
TotalCacheReadTokens int // Anthropic: tokens read from cache
TotalCachedTokens int // OpenAI: cached prompt tokens
}
// New creates a new loop Engine.
// maxContext is the model's maximum context window in tokens.
// Pass 0 for no limit enforcement.
func New(client *llm.Client, registry *tool.Registry, maxIterations int, systemMessage string, renderer *render.Renderer, maxContext int) *Engine {
return &Engine{
client: client,
registry: registry,
renderer: renderer,
maxIter: maxIterations,
system: systemMessage,
maxContext: maxContext,
maxConsecutiveToolErrors: make(map[string]int),
}
}
// SetSkillLoader sets the optional skill loader callback.
func (e *Engine) SetSkillLoader(sl SkillLoader) { e.skillLoader = sl }
// SetEpisodeContextFunc sets the optional per-turn episode search callback.
// When set, it is called once per new user message to search for relevant
// past session episodes. The returned context is injected as a system
// message before the LLM invocation.
func (e *Engine) SetEpisodeContextFunc(ef EpisodeContextFunc) { e.episodeCtx = ef }
// SetExtendedMemoryContextFunc sets the optional per-turn Extended Memory
// search callback. The returned context is injected as a system message
// after the legacy memory prompt block.
func (e *Engine) SetExtendedMemoryContextFunc(ef ExtendedMemoryContextFunc) { e.extendedCtx = ef }
// SetUserMessageHandler sets an optional callback invoked once per new user
// message. It is used by callers to trigger Extended Memory atom extraction.
func (e *Engine) SetUserMessageHandler(fn UserMessageHandler) { e.userMsgHandler = fn }
// SetInteractionMode sets how progress is surfaced.
// "off" suppresses all per-iteration render output except the final answer.
func (e *Engine) SetInteractionMode(mode string) { e.interactionMode = mode }
// SetSkillVerbose controls whether skill loading shows full banners (true)
// or condensed markers (false, default). Condensed saves context window space.
func (e *Engine) SetSkillVerbose(verbose bool) { e.skillVerbose = verbose }
// SetUntrustedWrapper sets a function that wraps externally-sourced content
// (skill context, episode context) with a nonce'd boundary before injecting it
// into the model's system context. When nil, that content is injected directly.
func (e *Engine) SetUntrustedWrapper(fn func(source, content string) string) {
e.wrapUntrusted = fn
}
// SetMemoryPromptFunc sets the optional memory prompt callback.
// When set, it is called before each LLM invocation to get fresh memory
// content. This ensures the agent sees the latest facts even if it
// modifies memory during a session.
func (e *Engine) SetMemoryPromptFunc(fn func() string) {
e.memoryPromptFunc = fn
if fn != nil {
e.baseSystem = e.system
}
}
// SetToolEventHandler sets the optional tool event callback for live streaming.
func (e *Engine) SetToolEventHandler(cb ToolEventHandler) { e.toolEventHandler = cb }
// SetNarrator sets the optional narrator for engaging mode.
// When nil (the default), tools render in verbose mode via the Renderer.
func (e *Engine) SetNarrator(n *narrate.Narrator) { e.narrator = n }
// SetIterationCallback sets the iteration progress callback.
// If nil, no callback is fired.
func (e *Engine) SetIterationCallback(cb IterationCallback) { e.iterationCallback = cb }
// SetMaxToolParallel sets the maximum concurrency for tool execution per
// iteration. 0 or negative = use default (4).
func (e *Engine) SetMaxToolParallel(n int) { e.MaxToolParallel = n }
// SetApprover sets the approval gate for dangerous operations.
// When set and the LLM returns multiple tool calls in one iteration, a
// single batch approval prompt is shown. Individual tool-level approval
// is bypassed when the batch is approved (if the approver supports
// SetTrustAll).
func (e *Engine) SetApprover(a danger.Approver) { e.approver = a }
// SetDangerousConfig provides the DangerousConfig for batch gate
// pre-classification. Without it, the batch gate cannot know which
// risk classes require approval and would skip pre-checking.
func (e *Engine) SetDangerousConfig(cfg *danger.DangerousConfig) { e.dangerousCfg = cfg }
// ── Token Estimation ─────────────────────────────────────────────────
//
// Zero-dependency heuristic: 1 token ≈ 4 chars for English text.
// JSON structure overhead is estimated per message and per tool call.
// These are conservative overestimates to prevent context limit errors.
// messageOverhead is the estimated tokens for JSON framing around a message.
const messageOverhead = 50
// toolCallOverhead is the estimated tokens for JSON framing around a tool call.
const toolCallOverhead = 30
// contextSafetyMargin is the fraction of MaxContext reserved for output.
// Input (messages + tools) should not exceed this fraction.
const contextSafetyMargin = 0.75
// estimateTokens returns a rough upper-bound token count for a string.
// Conservative: ~4 chars per token. Dense content (code, JSON) is
// closer to 2-3 chars/token; this is safe for both.
func estimateTokens(s string) int {
return (len(s) + 3) / 4
}
// estimateMessages returns the estimated total tokens for a slice of messages.
func estimateMessages(messages []llm.Message) int {
total := 0
for _, m := range messages {
total += messageOverhead
total += estimateTokens(m.Content)
total += estimateTokens(m.Name)
total += estimateTokens(m.ToolCallID)
for _, tc := range m.ToolCalls {
total += toolCallOverhead
total += estimateTokens(tc.ID)
total += estimateTokens(tc.Function.Name)
total += estimateTokens(tc.Function.Arguments)
}
}
return total
}
// estimateToolDefs returns the estimated tokens for tool definitions.
// These are sent with every request and count toward the context budget.
func estimateToolDefs(defs []llm.ToolDef) int {
total := 0
for _, d := range defs {
total += 30 // tool definition overhead
total += estimateTokens(d.Type)
total += estimateTokens(d.Function.Name)
total += estimateTokens(d.Function.Description)
}
return total
}
// contextBudget returns the input token budget (fraction of MaxContext).
func contextBudget(maxContext int) int {
if maxContext <= 0 {
return 0 // no limit
}
return int(float64(maxContext) * contextSafetyMargin)
}
// ── Context Trimming ─────────────────────────────────────────────────
// trimContext trims the message history to stay within the context budget.
// It preserves:
// - System message (always first, if present)
// - The first user message (the original task)
//
// It drops the oldest non-essential message triples (assistant tool-call
// message + its tool result(s)) to avoid orphaning tool results without
// their preceding tool_calls — DeepSeek rejects orphaned tool messages.
//
// When trimming occurs, a system message is injected to warn the agent
// that context was lost, preventing it from confidently operating on
// incomplete information.
//
// Performance: uses a running token total to avoid O(n²) re-scanning of
// the full message list on every iteration. Previously, estimateMessages
// was called at the top of the loop, re-summing ALL messages each time
// a single group was dropped. For large conversations near the context
// limit, this was O(n²) — now it's O(n).
func (e *Engine) trimContext(messages []llm.Message, toolDefs []llm.ToolDef) []llm.Message {
budget := contextBudget(e.maxContext)
if budget <= 0 {
return messages
}
// Estimate tool definitions once (they don't change between iterations)
defTokens := estimateToolDefs(toolDefs)
// Compute the running total ONCE — each group drop then subtracts only
// the dropped group's tokens instead of re-scanning all messages.
totalTokens := estimateMessages(messages) + defTokens
droppedGroups := 0
droppedTools := make(map[string]int)
for {
if totalTokens <= budget {
break
}
if len(messages) <= 2 {
break // can't trim further (need system + task at minimum)
}
// Find the first droppable index.
// Keep messages[0] if it's the system message.
// Keep the next message too (first user message = the task).
start := 0
if messages[0].Role == "system" {
start = 1 // keep system
}
start++ // keep system + task
if start >= len(messages) {
break
}
// Find the first complete droppable group starting at `start`.
// A group is either:
// - A standalone message (user text, assistant text)
// - An assistant tool_calls message + all following tool results
groupEnd := start + 1
if messages[start].Role == "assistant" && len(messages[start].ToolCalls) > 0 {
// Track which tools were called in dropped groups
for _, tc := range messages[start].ToolCalls {
droppedTools[tc.Function.Name]++
}
// Include all following tool result messages
for groupEnd < len(messages) && messages[groupEnd].Role == "tool" {
groupEnd++
}
}
droppedGroups++
// Subtract the dropped group's tokens from the running total.
// This avoids O(n²) behavior: we only scan the N messages being
// dropped, not the entire M-message list each iteration.
totalTokens -= estimateMessages(messages[start:groupEnd])
// (defTokens remains unchanged — tool defs don't get dropped)
// Drop the entire group atomically
messages = append(messages[:start], messages[groupEnd:]...)
}
// Inject context trim warning if we dropped messages
if droppedGroups > 0 && len(messages) > 1 {
warning := fmt.Sprintf(
"[Context trimmed: %d prior message group(s) dropped to stay within token budget. "+
"Some earlier tool calls and their results are no longer available. "+
"If the user references earlier work, ask them to summarize what was done.]",
droppedGroups,
)
// Insert after system message (index 0), before task (index 1)
trimMsg := llm.Message{Role: "system", Content: warning}
newMsgs := make([]llm.Message, 0, len(messages)+1)
newMsgs = append(newMsgs, messages[0])
newMsgs = append(newMsgs, trimMsg)
newMsgs = append(newMsgs, messages[1:]...)
messages = newMsgs
e.emitSignal(SignalEvent{
Type: "context_trimmed",
Detail: "proactive",
Count: droppedGroups,
})
}
return messages
}
// isContextLengthError returns true for API errors that indicate the
// input exceeded the model's context window. These errors are retryable
// with aggressive trimming rather than killing the session.
func isContextLengthError(err error) bool {
if err == nil {
return false
}
msg := err.Error()
// Common error patterns across providers:
// DeepSeek: "context_length_exceeded", "maximum context length"
// OpenAI: "maximum context length", "token limit"
// Anthropic: "input is too long", "context window"
return strings.Contains(msg, "context_length_exceeded") ||
strings.Contains(msg, "maximum context length") ||
strings.Contains(msg, "context length") ||
strings.Contains(msg, "token limit") ||
strings.Contains(msg, "context window") ||
strings.Contains(msg, "max_input_tokens") ||
strings.Contains(msg, "input length") ||
strings.Contains(msg, "too many tokens") ||
strings.Contains(msg, "input is too long") ||
strings.Contains(msg, "reduce the length")
}
// trimToSurvival drops all but the system prompt, first user message,
// and the most recent 2 complete turn groups. This is the nuclear option
// used when the API rejects the request as context-length-exceeded.
// Unlike trimContext which gives up when it can't stay under budget,
// trimToSurvival always produces a drastically reduced message list
// that nearly every model can handle.
func trimToSurvival(msgs []llm.Message) []llm.Message {
if len(msgs) <= 3 {
return msgs // already minimal enough
}
start := 0
if msgs[0].Role == "system" {
start = 1 // keep system
}
// Last user message (the current task/input) — always keep it.
var lastUser llm.Message
lastUserIdx := -1
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Role == "user" {
lastUser = msgs[i]
lastUserIdx = i
break
}
}
// Collect the last 2 complete assistant→tool groups before the user msg.
// Each group is a sub-slice in correct internal order: [system*, assistant, tool*].
var groups [][]llm.Message
seen := 0
for i := lastUserIdx - 1; i > start && seen < 2; i-- {
if msgs[i].Role == "assistant" && len(msgs[i].ToolCalls) > 0 {
var group []llm.Message
// Preceding system messages (corrections, warnings)
preStart := i - 1
for preStart > start && msgs[preStart].Role == "system" {
preStart--
}
for k := preStart + 1; k < i; k++ {
group = append(group, msgs[k])
}
// Assistant message with tool calls
group = append(group, msgs[i])
// Following tool results
for j := i + 1; j < len(msgs) && msgs[j].Role == "tool"; j++ {
group = append(group, msgs[j])
}
groups = append(groups, group)
i = preStart + 1 // skip past the group we just consumed
seen++
}
}
// Build survival set: system + task + recent groups + last user
// Calculate total messages across all groups for capacity hint
totalGroupMsgs := 0
for _, g := range groups {
totalGroupMsgs += len(g)
}
survival := make([]llm.Message, 0, start+1+totalGroupMsgs+1)
if start > 0 {
survival = append(survival, msgs[0]) // system message
}
// Add a context-warning system message
warning := "[Context trimmed to survive: the conversation history exceeded the model's context window. Earlier turns have been dropped. If you need information from earlier in the conversation, the agent may ask for a summary.]"
survival = append(survival, llm.Message{Role: "system", Content: warning})
// Add the recent groups in chronological order (groups were collected
// from newest to oldest, so reverse them while preserving each group's
// internal order: system* → assistant(tool_calls) → tool*).
for i := len(groups) - 1; i >= 0; i-- {
survival = append(survival, groups[i]...)
}
// Add the last user message
survival = append(survival, lastUser)
return survival
}
// ── Loop ──────────────────────────────────────────────────────────────
// Run executes the loop for a given task and returns the final response.
func (e *Engine) Run(ctx context.Context, task string) (string, error) {
e.memMsgIdx = -1
e.resetDedupKeys()
messages := []llm.Message{
{Role: "user", Content: task},
}
if e.system != "" {
messages = append([]llm.Message{{Role: "system", Content: e.system}}, messages...)
}
result, _, err := e.runLoop(ctx, messages)
return result, err
}
// RunWithMessages executes the agent loop starting from a pre-built
// message history. The messages must include the system prompt (if any),
// all prior conversation turns, and the new user message as the last
// entry. Returns the final answer plus the full updated message history
// so callers can persist it (e.g. to a session file).
//
// Use this for multi-turn conversations: load the session, append the
// new user message, call RunWithMessages, then save the returned messages.
func (e *Engine) RunWithMessages(ctx context.Context, messages []llm.Message) (string, []llm.Message, error) {
// Reset token accounting for this run
e.memMsgIdx = -1
e.resetDedupKeys()
e.TotalInputTokens = 0
e.TotalOutputTokens = 0
e.TotalCacheCreationTokens = 0
e.TotalCacheReadTokens = 0
e.TotalCachedTokens = 0
return e.runLoop(ctx, messages)
}
// resetDedupKeys clears the per-message dedup keys so a repeated user
// message in a later run (e.g. the REPL sending the same text twice)
// re-triggers the memory hooks (user-message handler, skill loading,
// episode recall, extended-memory recall).
func (e *Engine) resetDedupKeys() {
e.lastUserMsg = ""
e.lastSkillMsg = ""
e.lastEpiMsg = ""
e.lastExtMsg = ""
}
// trustAllSetter is implemented by approvers (wsApprover, TelegramApprover)
// whose tool-level prompts auto-pass while a batch approval grant is active.
type trustAllSetter interface{ SetTrustAll(bool) }
// runLoop is the shared core of Run and RunWithMessages.
// It runs the ReAct loop on the given messages and returns the final
// answer plus the complete updated message history.
func (e *Engine) runLoop(ctx context.Context, messages []llm.Message) (string, []llm.Message, error) {
tools := e.buildToolDefs()
startTime := time.Now()
// Reset per-session tool error tracking
e.maxConsecutiveToolErrors = make(map[string]int)
// Backstop: clear any batch trustAll grant when this run returns, even on
// early exit or panic, so it never leaks into a later prompt that reuses
// the same approver (wsApprover is per-connection, TelegramApprover is
// per-chat). The per-iteration reset below is the primary mechanism; this
// defer only covers abnormal exits mid-iteration.
if ta, ok := e.approver.(trustAllSetter); ok {
defer ta.SetTrustAll(false)
}
for i := 0; i < e.maxIter; i++ {
select {
case <-ctx.Done():
return "", messages, ctx.Err()
default:
}
// Trim context to stay within model's context window
messages = e.trimContext(messages, tools)
// Resync memMsgIdx after trimContext — when trimContext injects a
// context-warning message at index 1, all subsequent messages shift
// right by 1, making e.memMsgIdx point to the warning instead of
// memory. Detect this by checking if the message at our tracked
// position is a trim warning.
if e.memMsgIdx > 0 && e.memMsgIdx < len(messages) {
if strings.Contains(messages[e.memMsgIdx].Content, "[Context trimmed:") {
// Trim warning was injected before our memory message.
// The actual memory message is now at memMsgIdx + 1.
e.memMsgIdx++
}
}
// After trimContext, verify the memory message still exists at the
// tracked position. trimContext starts dropping from index 2 onward,
// and the memory message can shift into that range after a trim
// warning is injected (shifting it from index 1 to 2). Once at index
// 2, it can be dropped by subsequent trimContext calls, leaving
// memMsgIdx pointing to the wrong message (a user/assistant message
// that shifted into that slot). When this happens, reset memMsgIdx
// so the memory is re-inserted at the correct position.
if e.memMsgIdx >= 0 && e.memMsgIdx < len(messages) {
if messages[e.memMsgIdx].Role != "system" {
// Memory message was dropped — re-insert on next update.
e.memMsgIdx = -1
}
}
// Notify callers when a new user message arrives. This triggers
// Extended Memory atom extraction without coupling the loop to the
// memory subsystem.
if e.userMsgHandler != nil {
if userMsg := lastUserMessage(messages); userMsg != "" && userMsg != e.lastUserMsg {
e.lastUserMsg = userMsg
e.userMsgHandler(ctx, userMsg)
}
}
// Load relevant skills based on latest user input (once per message)
if e.skillLoader != nil {
if userMsg := lastUserMessage(messages); userMsg != "" && userMsg != e.lastSkillMsg {
// Assign the dedup key unconditionally — even when the loader
// finds no match — so a no-match doesn't re-run the (potentially
// slow) skill matcher on every remaining iteration of the turn.
e.lastSkillMsg = userMsg
if skillContext := e.skillLoader(userMsg); skillContext != "" {
// Inject skill context as a system message right before the user message.
// The skill manager gates NeedsReview/tainted skills, but we treat any
// loaded skill content as externally-sourced and wrap it with the
// caller-provided untrusted wrapper as defense in depth.
wrappedContent := skillContext
if e.wrapUntrusted != nil {
wrappedContent = e.wrapUntrusted("skill", skillContext)
}
if fn := IngestRecorderFrom(ctx); fn != nil {
fn("skill", skillContext)
}
insertIdx := len(messages)
for j := len(messages) - 1; j >= 0; j-- {
if messages[j].Role == "system" && j != 0 {
insertIdx = j + 1
break
}
}
var wrappedSkill string
if e.skillVerbose {
wrappedSkill = "═══ SKILL LOADED (reference) ═══\n" +
wrappedContent +
"\n═══ END SKILL ═══"
} else {
wrappedSkill = wrappedContent
}
skillMsg := llm.Message{Role: "system", Content: wrappedSkill}
// Pre-allocate and copy to avoid nested append allocations
newMsgs := make([]llm.Message, 0, len(messages)+1)
newMsgs = append(newMsgs, messages[:insertIdx]...)
newMsgs = append(newMsgs, skillMsg)
newMsgs = append(newMsgs, messages[insertIdx:]...)
messages = newMsgs
}
}
}
// Search relevant past session episodes based on latest user input.
// Only runs once per new user message (same dedup as skill loading).
if e.episodeCtx != nil {
if userMsg := lastUserMessage(messages); userMsg != "" && userMsg != e.lastEpiMsg {
// Assign the dedup key unconditionally — even when recall finds
// no match — so a no-match doesn't re-run the (potentially slow
// HTTP embed) episode search on every iteration of the turn.
e.lastEpiMsg = userMsg
if episodeContext := e.episodeCtx(userMsg); episodeContext != "" {
// Episode context comes from past session content and crosses the
// trust boundary; wrap it as untrusted before injecting.
wrappedContext := episodeContext
if e.wrapUntrusted != nil {
wrappedContext = e.wrapUntrusted("episode", episodeContext)
}
if fn := IngestRecorderFrom(ctx); fn != nil {
fn("episode", episodeContext)
}
// Inject episode context as a system message before the user message
insertIdx := len(messages)
for j := len(messages) - 1; j >= 0; j-- {
if messages[j].Role == "system" && j != 0 {
insertIdx = j + 1
break
}
}
epMsg := llm.Message{Role: "system", Content: wrappedContext}
newMsgs := make([]llm.Message, 0, len(messages)+1)
newMsgs = append(newMsgs, messages[:insertIdx]...)
newMsgs = append(newMsgs, epMsg)
newMsgs = append(newMsgs, messages[insertIdx:]...)
messages = newMsgs
}
}
}
// Refresh memory content before each LLM call so the agent sees
// the latest facts even if it mutated memory during this session.
// Memory is injected as a separate system message (messages[1] or
// later) so that messages[0] (baseSystem) remains stable across
// turns — letting DeepSeek/Anthropic prompt caching keep it cached.
if e.memoryPromptFunc != nil {
if memBlock := e.memoryPromptFunc(); memBlock != "" {
// Keep messages[0] as the stable baseSystem (never modified).
if len(messages) > 0 && messages[0].Role == "system" {
messages[0].Content = e.baseSystem
}
memMsg := llm.Message{Role: "system", Content: memBlock}
if e.memMsgIdx >= 0 && e.memMsgIdx < len(messages) {
// Update existing memory slot — keeps position stable.
messages[e.memMsgIdx].Content = memBlock
} else {
// First time: insert memory message after base system.
insertAt := 1
messages = append(messages[:insertAt],
append([]llm.Message{memMsg}, messages[insertAt:]...)...)
e.memMsgIdx = insertAt
}
} else if e.memMsgIdx >= 0 && e.memMsgIdx < len(messages) {
// No memory block — remove the memory message if present.
messages = append(messages[:e.memMsgIdx], messages[e.memMsgIdx+1:]...)
e.memMsgIdx = -1
}
}
// Inject Extended Memory context after the legacy memory prompt block.
// Uses a dedicated dedup key so repeated queries do not suppress new
// user messages.
if e.extendedCtx != nil {
if userMsg := lastUserMessage(messages); userMsg != "" && userMsg != e.lastExtMsg {
if extContext := e.extendedCtx(ctx, userMsg); extContext != "" {
wrapped := extContext
if e.wrapUntrusted != nil {
wrapped = e.wrapUntrusted("extended_memory", extContext)
}
if fn := IngestRecorderFrom(ctx); fn != nil {
fn("extended_memory", extContext)
}
insertIdx := len(messages)
for j := len(messages) - 1; j >= 0; j-- {
if messages[j].Role == "system" && j != 0 {
insertIdx = j + 1
break
}
}
extMsg := llm.Message{Role: "system", Content: wrapped}
newMsgs := make([]llm.Message, 0, len(messages)+1)
newMsgs = append(newMsgs, messages[:insertIdx]...)
newMsgs = append(newMsgs, extMsg)
newMsgs = append(newMsgs, messages[insertIdx:]...)
messages = newMsgs
}
e.lastExtMsg = userMsg
}
}
// THINK (timed)
start := time.Now()
// Apply prompt caching markers when enabled
var systemBlocks []llm.SystemBlock
callMsgs := messages
if e.PromptCaching {
callMsgs, systemBlocks = llm.ApplyCacheMarkers(messages)
}
result, err := e.client.Call(ctx, callMsgs, systemBlocks, tools)
latency := time.Since(start)
if err != nil {
// Context-length-exceeded errors: don't die — try aggressive
// trimming and retry once. The trimContext at the top of the
// loop may have been too conservative (75% budget) or the
// provider's reported context window may be smaller than
// the actual model limit.
if isContextLengthError(err) {
trimmed := trimToSurvival(messages)
if len(trimmed) < len(messages) {
e.emitSignal(SignalEvent{
Type: "context_trimmed",
Detail: "survival",
Count: len(messages) - len(trimmed),
})
messages = trimmed
// Reset memory index — trimToSurvival drops it.
e.memMsgIdx = -1
// Inject survival warning as the final message
// so the agent knows context was lost.
messages = append(messages, llm.Message{
Role: "system",
Content: "[Context survival mode: the conversation was aggressively reduced to fit the model's context window. Continue from where you left off using the most recent context available.]",
})
continue // retry this iteration
}
}
return "", messages, fmt.Errorf("iteration %d: %w", i, err)
}
// Render turn statistics (re-draw iteration header with stats)
if e.renderer != nil && e.interactionMode != "off" {
e.renderer.Iteration(i+1, e.maxIter, latency, result.InputTokens, result.OutputTokens, 0)
}
// Accumulate token usage across iterations
e.TotalInputTokens += result.InputTokens
e.TotalOutputTokens += result.OutputTokens
// Accumulate cache metrics
// Accumulate cache metrics across iterations
e.TotalCacheCreationTokens += result.CacheCreationTokens
e.TotalCacheReadTokens += result.CacheReadTokens
e.TotalCachedTokens += result.CachedTokens
// No tool calls = final answer
if len(result.ToolCalls) == 0 {
if e.renderer != nil && e.interactionMode != "off" {
// Show the model's reasoning for the final answer before the
// answer itself. For intermediate iterations this is handled
// separately (line ~752); here it would be dropped otherwise.
if result.ReasoningContent != "" {
e.renderer.Thinking(result.ReasoningContent)
}
e.renderer.FinalAnswer(result.Content)
e.renderer.Summary(
e.TotalInputTokens,
e.TotalOutputTokens,
e.TotalCacheCreationTokens,
e.TotalCacheReadTokens,
e.TotalCachedTokens,
)
}
// Fire iteration callback with final answer signal.
// ReasoningContent is included so callers (Telegram, future UIs)
// can display the model's reasoning for the final turn — previously
// it was omitted, causing thinking to be silently dropped.
if e.iterationCallback != nil {
e.iterationCallback(IterationInfo{
Turn: i + 1,
MaxTurns: e.maxIter,
ToolNames: nil,
InputTokens: e.TotalInputTokens,
OutputTokens: e.TotalOutputTokens,
CacheCreationTokens: e.TotalCacheCreationTokens,
CacheReadTokens: e.TotalCacheReadTokens,
CachedTokens: e.TotalCachedTokens,
TotalLatency: time.Since(startTime),
HasFinalAnswer: true,
ReasoningContent: result.ReasoningContent,
})
}
// Append final assistant message so callers (e.g. WebUI) get
// the final text in the messages slice and can stream it.
messages = append(messages, llm.Message{
Role: "assistant",
Content: result.Content,
ReasoningContent: result.ReasoningContent,
})
return result.Content, messages, nil
}
// Render the model's thinking (reasoning before tool calls)
// In engaging mode, narrate the thinking; in verbose mode, show raw content.
if e.narrator != nil && result.Content != "" {
if msg := e.narrator.ThinkingMessage(result.Content); msg != "" {
if e.renderer != nil {
e.renderer.NarratorMessage(msg)
}
}
} else if e.renderer != nil && result.Content != "" && e.interactionMode != "off" {
e.renderer.Thinking(result.Content)
}
// Build assistant message with tool calls
assistantMsg := llm.Message{
Role: "assistant",
Content: result.Content,
ReasoningContent: result.ReasoningContent,
ToolCalls: result.ToolCalls,
}
messages = append(messages, assistantMsg)
// ACT: execute each tool call in parallel with bounded concurrency
toolNames := make([]string, 0, len(result.ToolCalls))
for _, tc := range result.ToolCalls {
toolNames = append(toolNames, tc.Function.Name)
}
// Fire iteration callback BEFORE tool execution so UIs can show
// the LLM's reasoning and which tools are about to run.
if e.iterationCallback != nil {
e.iterationCallback(IterationInfo{
Turn: i + 1,
MaxTurns: e.maxIter,
ToolNames: toolNames,
InputTokens: e.TotalInputTokens,
OutputTokens: e.TotalOutputTokens,
CacheCreationTokens: e.TotalCacheCreationTokens,
CacheReadTokens: e.TotalCacheReadTokens,
CachedTokens: e.TotalCachedTokens,
TotalLatency: time.Since(startTime),
HasFinalAnswer: false,
ReasoningContent: result.ReasoningContent,
IsPreTool: true,
})
}
// Phase 1: fire all tool_call events synchronously (rendering + events)
for _, tc := range result.ToolCalls {
if e.narrator != nil {
if msg := e.narrator.ToolCallMessage(tc.Function.Name, tc.Function.Arguments); msg != "" {
if e.renderer != nil {
e.renderer.NarratorMessage(msg)
}
}
} else if e.renderer != nil && e.interactionMode != "off" {
e.renderer.ToolCall(tc.Function.Name, tc.Function.Arguments)
}
if e.toolEventHandler != nil {
e.toolEventHandler("tool_call", tc.Function.Name, tc.Function.Arguments)
}
}
// Phase 1.5: batch approval gate
// When an approver is set and the LLM returned multiple tool calls,
// present a single approval prompt for the entire batch instead of
// N individual prompts, but ONLY for tools that actually require
// approval. If denied, all tool calls are rejected without executing
// anything. If approved, the approver's trustAll flag is set so
// individual tool-level PromptCommand calls auto-pass.
batchDenied := false
// trustAllApprover holds the approver whose trustAll flag was set by an
// approved batch this iteration, so it can be reset once this
// iteration's tools have executed. It MUST be reset per-iteration
// (not via defer, which only fires when runLoop returns) — otherwise a
// single approved batch would auto-approve every dangerous tool for the
// remainder of the run.
var trustAllApprover trustAllSetter
if e.approver != nil && len(result.ToolCalls) > 1 {
// Classify each tool call and filter to only those needing approval.
type riskyCall struct {
idx int
name string