-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop_test.go
More file actions
2385 lines (2123 loc) · 80.9 KB
/
Copy pathloop_test.go
File metadata and controls
2385 lines (2123 loc) · 80.9 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
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/BackendStack21/odek/internal/danger"
"github.com/BackendStack21/odek/internal/llm"
"github.com/BackendStack21/odek/internal/render"
"github.com/BackendStack21/odek/internal/tool"
)
// fakeTool is a simple tool for testing.
type fakeTool struct {
name string
description string
output string
}
func (f *fakeTool) Name() string { return f.name }
func (f *fakeTool) Description() string { return f.description }
func (f *fakeTool) Schema() any {
return map[string]any{
"type": "object",
"properties": map[string]any{},
}
}
func (f *fakeTool) Call(args string) (string, error) { return f.output, nil }
func TestEngine_Run_SimpleAnswer(t *testing.T) {
// Fake server that returns a final answer immediately (no tool calls).
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"choices":[{"message":{"content":"Hello from odek!"}}]}`)
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
registry := tool.NewRegistry(nil)
engine := New(client, registry, 10, "", nil, 0)
result, err := engine.Run(context.Background(), "Say hello")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if result != "Hello from odek!" {
t.Errorf("result = %q, want %q", result, "Hello from odek!")
}
}
func TestEngine_Run_ToolCallLoop(t *testing.T) {
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
if callCount == 1 {
// First call: model requests a tool
fmt.Fprint(w, `{
"choices":[{
"message":{
"content":"Let me check.",
"tool_calls":[{
"id":"call_1",
"function":{
"name":"echo",
"arguments":"{\"text\":\"hello\"}"
}
}]
}
}]
}`)
} else {
// Second call: final answer
fmt.Fprint(w, `{"choices":[{"message":{"content":"The tool said: hello output"}}]}`)
}
}))
defer server.Close()
echoTool := &fakeTool{name: "echo", description: "echoes input", output: "hello output"}
registry := tool.NewRegistry([]tool.Tool{echoTool})
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, registry, 10, "", nil, 0)
result, err := engine.Run(context.Background(), "Echo hello")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if result != "The tool said: hello output" {
t.Errorf("result = %q, want %q", result, "The tool said: hello output")
}
if callCount != 2 {
t.Errorf("expected 2 LLM calls, got %d", callCount)
}
}
func TestEngine_Run_MaxIterations(t *testing.T) {
// Server that always requests a tool call, never gives a final answer.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{
"choices":[{
"message":{
"content":"",
"tool_calls":[{
"id":"call_1",
"function":{
"name":"echo",
"arguments":"{}"
}
}]
}
}]
}`)
}))
defer server.Close()
echoTool := &fakeTool{name: "echo", description: "echo", output: "ok"}
registry := tool.NewRegistry([]tool.Tool{echoTool})
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, registry, 3, "", nil, 0)
_, err := engine.Run(context.Background(), "Loop forever")
if err == nil {
t.Fatal("expected max iterations error")
}
}
func TestEngine_Run_ContextCancellation(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"choices":[{"message":{"content":"answer"}}]}`)
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, tool.NewRegistry(nil), 10, "", nil, 0)
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel immediately
_, err := engine.Run(ctx, "task")
if err == nil {
t.Fatal("expected context cancellation error")
}
}
func TestEngine_Run_SystemMessage(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Verify the system message is injected as the first message.
var body struct {
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err == nil {
if len(body.Messages) > 0 && body.Messages[0].Role == "system" {
if body.Messages[0].Content != "You are a test bot." {
t.Errorf("system message = %q, want %q", body.Messages[0].Content, "You are a test bot.")
}
} else {
t.Error("system message not found or wrong role")
}
}
fmt.Fprint(w, `{"choices":[{"message":{"content":"ok"}}]}`)
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, tool.NewRegistry(nil), 10, "You are a test bot.", nil, 0)
result, err := engine.Run(context.Background(), "hi")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if result != "ok" {
t.Errorf("result = %q, want %q", result, "ok")
}
}
func TestEngine_Run_ToolNotFound(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{
"choices":[{
"message":{
"content":"",
"tool_calls":[{
"id":"call_x",
"function":{
"name":"nonexistent",
"arguments":"{}"
}
}]
}
}]
}`)
}))
defer server.Close()
// No tools registered — the tool call will fail
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, tool.NewRegistry(nil), 10, "", nil, 0)
// The loop should handle the missing tool gracefully — the tool error
// is fed back to the model as a tool response message. The test server
// only returns one response, so we'll hit max iterations.
_, err := engine.Run(context.Background(), "use missing tool")
if err == nil {
t.Fatal("expected error (max iterations or similar)")
}
}
func TestLastUserMessage_NoMessages(t *testing.T) {
result := lastUserMessage(nil)
if result != "" {
t.Errorf("lastUserMessage(nil) = %q, want empty", result)
}
result = lastUserMessage([]llm.Message{})
if result != "" {
t.Errorf("lastUserMessage([]) = %q, want empty", result)
}
}
func TestLastUserMessage_FindsLatest(t *testing.T) {
msgs := []llm.Message{
{Role: "user", Content: "first"},
{Role: "assistant", Content: "answer"},
{Role: "user", Content: "second"},
}
result := lastUserMessage(msgs)
if result != "second" {
t.Errorf("lastUserMessage = %q, want %q", result, "second")
}
}
func TestEngine_RunWithMessages(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"choices":[{"message":{"content":"used RunWithMessages"}}],"usage":{"prompt_tokens":50,"completion_tokens":10}}`)
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, tool.NewRegistry(nil), 10, "", nil, 0)
msgs := []llm.Message{
{Role: "system", Content: "bot"},
{Role: "user", Content: "task"},
}
result, _, err := engine.RunWithMessages(context.Background(), msgs)
if err != nil {
t.Fatalf("RunWithMessages error: %v", err)
}
if result != "used RunWithMessages" {
t.Errorf("result = %q, want %q", result, "used RunWithMessages")
}
}
func TestEngine_RunWithMessages_TokenAccumulation(t *testing.T) {
// Mock LLM that returns usage stats and triggers tool calls to
// exercise multi-iteration accumulation.
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.Header().Set("Content-Type", "application/json")
if callCount <= 2 {
// Tool call responses with usage
fmt.Fprintf(w, `{"choices":[{"message":{"content":"Step %d.","tool_calls":[{"id":"c_%d","function":{"name":"echo","arguments":"{}"}}]}}],"usage":{"prompt_tokens":%d,"completion_tokens":%d}}`,
callCount, callCount, callCount*100, callCount*20)
} else {
// Final answer with usage
fmt.Fprint(w, `{"choices":[{"message":{"content":"done."}}],"usage":{"prompt_tokens":500,"completion_tokens":50}}`)
}
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
registry := tool.NewRegistry([]tool.Tool{&fakeTool{name: "echo", description: "echo", output: "pong"}})
engine := New(client, registry, 10, "", nil, 0)
msgs := []llm.Message{
{Role: "system", Content: "bot"},
{Role: "user", Content: "do it"},
}
_, _, err := engine.RunWithMessages(context.Background(), msgs)
if err != nil {
t.Fatalf("RunWithMessages error: %v", err)
}
// Iteration tokens: iter1=100/20, iter2=200/40, iter3=500/50
wantInput := 100 + 200 + 500 // 800
wantOutput := 20 + 40 + 50 // 110
if engine.TotalInputTokens != wantInput {
t.Errorf("TotalInputTokens = %d, want %d", engine.TotalInputTokens, wantInput)
}
if engine.TotalOutputTokens != wantOutput {
t.Errorf("TotalOutputTokens = %d, want %d", engine.TotalOutputTokens, wantOutput)
}
// Verify token fields reset on a second call (not cumulative)
callCount = 0
engine.RunWithMessages(context.Background(), msgs)
// After reset, should be 800 again (same pattern), NOT 1600 (cumulative)
if engine.TotalInputTokens != 800 {
t.Errorf("TotalInputTokens after reset = %d, want 800 (not cumulative across calls)", engine.TotalInputTokens)
}
if engine.TotalOutputTokens != 110 {
t.Errorf("TotalOutputTokens after reset = %d, want 110 (not cumulative)", engine.TotalOutputTokens)
}
}
func TestEngine_BuildToolDefs(t *testing.T) {
t1 := &fakeTool{name: "read", description: "read files"}
t2 := &fakeTool{name: "write", description: "write files"}
registry := tool.NewRegistry([]tool.Tool{t1, t2})
engine := New(nil, registry, 10, "", nil, 0)
defs := engine.buildToolDefs()
if len(defs) != 2 {
t.Fatalf("expected 2 tool defs, got %d", len(defs))
}
names := map[string]bool{}
for _, d := range defs {
if d.Type != "function" {
t.Errorf("ToolDef.Type = %q, want %q", d.Type, "function")
}
names[d.Function.Name] = true
}
if !names["read"] || !names["write"] {
t.Errorf("missing expected tool names: got %v", names)
}
}
func TestEngine_BuildToolDefs_StringSchema(t *testing.T) {
// Test the string schema path in buildToolDefs
st := &stringSchemaTool{name: "custom", description: "custom tool", schemaStr: `{"type":"object"}`}
registry := tool.NewRegistry([]tool.Tool{st})
engine := New(nil, registry, 10, "", nil, 0)
defs := engine.buildToolDefs()
if len(defs) != 1 {
t.Fatalf("expected 1 tool def, got %d", len(defs))
}
if defs[0].Function.Name != "custom" {
t.Errorf("name = %q, want 'custom'", defs[0].Function.Name)
}
}
func TestEngine_BuildToolDefs_EmptyStringSchema(t *testing.T) {
st := &stringSchemaTool{name: "empty", description: "empty", schemaStr: ""}
registry := tool.NewRegistry([]tool.Tool{st})
engine := New(nil, registry, 10, "", nil, 0)
defs := engine.buildToolDefs()
if len(defs) != 1 {
t.Fatalf("expected 1 tool def, got %d", len(defs))
}
// Empty string schema should produce empty properties object
}
// stringSchemaTool returns Schema() as a string instead of map[string]any
type stringSchemaTool struct {
name string
description string
schemaStr string
}
func (s *stringSchemaTool) Name() string { return s.name }
func (s *stringSchemaTool) Description() string { return s.description }
func (s *stringSchemaTool) Schema() any { return s.schemaStr }
func (s *stringSchemaTool) Call(args string) (string, error) { return "ok", nil }
// Test context cancellation inside the iteration loop (not before start).
func TestEngine_Run_ContextCancelDuringLoop(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Cancel context during the first LLM call. The loop processes
// the tool call synchronously, then on the next iteration
// ctx.Done() fires.
cancel()
fmt.Fprint(w, `{
"choices":[{
"message":{
"content":"",
"tool_calls":[{
"id":"call_1",
"function":{
"name":"echo",
"arguments":"{}"
}
}]
}
}]
}`)
}))
defer server.Close()
echoTool := &fakeTool{name: "echo", description: "echo", output: "ok"}
registry := tool.NewRegistry([]tool.Tool{echoTool})
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, registry, 10, "", nil, 0)
_, err := engine.Run(ctx, "task")
if err == nil {
t.Fatal("expected context cancellation error")
}
}
// Test the path where tool.Call() returns an error (lines 74-75 in loop.go).
func TestEngine_Run_ToolCallError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{
"choices":[{
"message":{
"content":"",
"tool_calls":[{
"id":"call_1",
"function":{
"name":"failing",
"arguments":"{}"
}
}]
}
}]
}`)
}))
defer server.Close()
failingTool := &errorTool{name: "failing", description: "always fails"}
registry := tool.NewRegistry([]tool.Tool{failingTool})
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, registry, 10, "", nil, 0)
// Tool error is fed back as a tool response; server only returns one
// response, so we hit max iterations.
_, err := engine.Run(context.Background(), "use failing tool")
if err == nil {
t.Fatal("expected error (max iterations)")
}
}
// errorTool returns an error from Call().
type errorTool struct {
name string
description string
}
func (e *errorTool) Name() string { return e.name }
func (e *errorTool) Description() string { return e.description }
func (e *errorTool) Schema() any { return map[string]any{"type": "object"} }
func (e *errorTool) Call(args string) (string, error) { return "", fmt.Errorf("tool error") }
// ═════════════════════════════════════════════════════════════════════
// Context Trimming Tests
// ═════════════════════════════════════════════════════════════════════
func TestEstimateTokens_Empty(t *testing.T) {
if n := estimateTokens(""); n != 0 {
t.Errorf("estimateTokens('') = %d, want 0", n)
}
}
func TestEstimateTokens_Short(t *testing.T) {
// "hello" is 5 chars → (5+3)/4 = 2 tokens (conservative overestimate)
if n := estimateTokens("hello"); n != 2 {
t.Errorf("estimateTokens('hello') = %d, want 2", n)
}
}
func TestEstimateTokens_Long(t *testing.T) {
// ~4 chars per token — 1000 chars should be ~250 tokens
n := estimateTokens(strings.Repeat("x", 1000))
if n < 200 || n > 300 {
t.Errorf("estimateTokens(1000 chars) = %d, want ~250", n)
}
}
func TestEstimateMessages_Empty(t *testing.T) {
if n := estimateMessages(nil); n != 0 {
t.Errorf("estimateMessages(nil) = %d, want 0", n)
}
}
func TestEstimateMessages_Single(t *testing.T) {
msg := []llm.Message{{Role: "user", Content: "hello"}}
n := estimateMessages(msg)
// 50 overhead + 2 tokens for "hello" = 52
if n < 50 || n > 55 {
t.Errorf("estimateMessages(single) = %d, want ~52", n)
}
}
func TestEstimateMessages_WithToolCalls(t *testing.T) {
msg := []llm.Message{{
Role: "assistant",
Content: "Let me check",
ToolCalls: []llm.ToolCall{{
ID: "call_1",
Type: "function",
Function: struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
}{Name: "shell", Arguments: `{"cmd":"ls"}`},
}},
}}
n := estimateMessages(msg)
if n < 80 {
t.Errorf("estimateMessages(with tool call) = %d, want >80", n)
}
}
func TestContextBudget_NoLimit(t *testing.T) {
if n := contextBudget(0); n != 0 {
t.Errorf("contextBudget(0) = %d, want 0", n)
}
}
func TestContextBudget_WithLimit(t *testing.T) {
// 131072 * 0.75 = 98304
if n := contextBudget(131072); n != 98304 {
t.Errorf("contextBudget(131072) = %d, want 98304", n)
}
}
func TestTrimContext_NoLimit(t *testing.T) {
engine := &Engine{maxContext: 0}
msgs := []llm.Message{
{Role: "system", Content: "You are a bot."},
{Role: "user", Content: "hello"},
}
result := engine.trimContext(msgs, nil)
if len(result) != 2 {
t.Errorf("trimContext with no limit should not change messages, got %d", len(result))
}
}
func TestTrimContext_UnderBudget(t *testing.T) {
// Large budget — messages fit easily
engine := &Engine{maxContext: 1_000_000}
msgs := []llm.Message{
{Role: "system", Content: "You are a bot."},
{Role: "user", Content: "hello"},
{Role: "assistant", Content: "Hi there", ToolCalls: nil},
{Role: "tool", Content: "result", ToolCallID: "call_1"},
}
result := engine.trimContext(msgs, nil)
if len(result) != 4 {
t.Errorf("trimContext under budget should keep all messages, got %d", len(result))
}
}
func TestTrimContext_OverBudget(t *testing.T) {
// Very tight budget — forces trimming
engine := &Engine{maxContext: 200}
msgs := []llm.Message{
{Role: "system", Content: "You are a helpful assistant. Be concise."},
{Role: "user", Content: "Explain how the quantum fourier transform works in detail"},
{Role: "assistant", Content: strings.Repeat("thinking about this... ", 20)},
{Role: "tool", Content: strings.Repeat("some result data ", 20), ToolCallID: "call_1"},
{Role: "assistant", Content: strings.Repeat("more reasoning... ", 20)},
{Role: "tool", Content: strings.Repeat("more data ", 20), ToolCallID: "call_2"},
{Role: "assistant", Content: strings.Repeat("final reasoning... ", 20)},
{Role: "tool", Content: strings.Repeat("final data ", 20), ToolCallID: "call_3"},
}
result := engine.trimContext(msgs, nil)
// Should have preserved system + task (first user)
if len(result) < 2 {
t.Errorf("trimContext should keep at least system + task, got %d", len(result))
}
if result[0].Role != "system" {
t.Errorf("trimContext should keep system message first, got role=%q", result[0].Role)
}
if result[1].Role != "system" {
t.Errorf("trimContext should inject trim warning at index 1, got role=%q", result[1].Role)
}
if result[2].Role != "user" {
t.Errorf("trimContext should keep task message at index 2, got role=%q", result[2].Role)
}
// Should have fewer messages than original (excluding the injected warning)
if len(result)-1 >= len(msgs) {
t.Errorf("trimContext should reduce messages, got %d >= %d", len(result), len(msgs))
}
}
func TestTrimContext_VeryTightBudget(t *testing.T) {
// Extremely tight budget — still should keep system + task
engine := &Engine{maxContext: 100}
msgs := []llm.Message{
{Role: "system", Content: "You are a bot."},
{Role: "user", Content: "Hello world, this is a task message that is somewhat long"},
{Role: "assistant", Content: strings.Repeat("data ", 50)},
{Role: "tool", Content: strings.Repeat("result ", 50), ToolCallID: "call_1"},
}
result := engine.trimContext(msgs, nil)
// Must keep system + task at minimum
if len(result) < 2 {
t.Errorf("trimContext(VeryTight) should keep system + task, got %d", len(result))
}
if result[0].Role != "system" {
t.Errorf("trimContext(VeryTight) should keep system first")
}
if result[1].Role != "system" {
t.Errorf("trimContext(VeryTight) should inject trim warning at index 1, got %q", result[1].Role)
}
if result[2].Role != "user" {
t.Errorf("trimContext(VeryTight) should keep task at index 2, got %q", result[2].Role)
}
}
func TestTrimContext_NoSystemMessage(t *testing.T) {
engine := &Engine{maxContext: 150}
msgs := []llm.Message{
{Role: "user", Content: "This is a long task message that takes up many tokens"},
{Role: "assistant", Content: strings.Repeat("data ", 30)},
{Role: "tool", Content: strings.Repeat("result ", 30), ToolCallID: "call_1"},
}
result := engine.trimContext(msgs, nil)
// Without system, keep at least the task
if len(result) < 1 {
t.Errorf("trimContext(no system) should keep task, got %d", len(result))
}
if result[0].Role != "user" {
t.Errorf("trimContext(no system) should keep task first, got %q", result[0].Role)
}
}
func TestEstimateToolDefs_Empty(t *testing.T) {
if n := estimateToolDefs(nil); n != 0 {
t.Errorf("estimateToolDefs(nil) = %d, want 0", n)
}
}
func TestEstimateToolDefs_Single(t *testing.T) {
defs := []llm.ToolDef{{
Type: "function",
Function: llm.FunctionDef{
Name: "shell",
Description: "run a shell command",
},
}}
n := estimateToolDefs(defs)
if n < 30 {
t.Errorf("estimateToolDefs(single) = %d, want >30", n)
}
}
func TestTrimContext_IncludesToolDefTokens(t *testing.T) {
// Budget that forces trimming when tool defs are included
engine := &Engine{maxContext: 300}
msgs := []llm.Message{
{Role: "system", Content: "You are a bot."},
{Role: "user", Content: "do the thing"},
{Role: "assistant", Content: strings.Repeat("long thinking ", 30)},
{Role: "tool", Content: strings.Repeat("long result ", 30), ToolCallID: "call_1"},
}
defs := []llm.ToolDef{{
Type: "function",
Function: llm.FunctionDef{
Name: "shell",
Description: strings.Repeat("very long description that takes up tokens ", 10),
},
}}
result := engine.trimContext(msgs, defs)
if len(result) >= len(msgs) {
t.Errorf("trimContext with tool defs should trim, got %d >= %d", len(result), len(msgs))
}
}
func TestEngine_SkillLoader_CalledOncePerInput(t *testing.T) {
// Regression: SkillLoader must fire only once per unique user message,
// not once per iteration. Verifies the skill injection leak fix.
skillLoadCount := 0
var loadedInput string
skillLoader := func(userInput string) string {
skillLoadCount++
loadedInput = userInput
return "injected skill content"
}
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
if callCount == 1 {
// First iteration: request a tool call
fmt.Fprint(w, `{
"choices":[{
"message":{
"content":"Let me think.",
"tool_calls":[{
"id":"call_1",
"function":{
"name":"echo",
"arguments":"{}"
}
}]
}
}]
}`)
} else {
// Second iteration: final answer
fmt.Fprint(w, `{"choices":[{"message":{"content":"done"}}]}`)
}
}))
defer server.Close()
echoTool := &fakeTool{name: "echo", description: "echo", output: "ok"}
registry := tool.NewRegistry([]tool.Tool{echoTool})
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, registry, 10, "", nil, 0)
engine.SetSkillLoader(skillLoader)
result, err := engine.Run(context.Background(), "do the task")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if result != "done" {
t.Errorf("result = %q, want %q", result, "done")
}
// SkillLoader should have been called exactly once,
// not once per iteration (which would be 2+)
if skillLoadCount != 1 {
t.Errorf("SkillLoader called %d times, want 1 (should dedup per input)", skillLoadCount)
}
if loadedInput != "do the task" {
t.Errorf("loadedInput = %q, want %q", loadedInput, "do the task")
}
if callCount != 2 {
t.Errorf("LLM called %d times, want 2", callCount)
}
}
func TestEngine_ToolEventHandler(t *testing.T) {
// Verify that ToolEventHandler fires tool_call before and tool_result
// after each tool invocation, and does so live (during the loop).
var events []string
var eventData []string
eventHandler := func(event, name, data string) {
events = append(events, event)
eventData = append(eventData, name)
}
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
if callCount == 1 {
// First iteration: request a tool call
fmt.Fprint(w, `{
"choices":[{
"message":{
"content":"Checking.",
"tool_calls":[{
"id":"call_1",
"function":{
"name":"echo",
"arguments":"{}"
}
}]
}
}]
}`)
} else {
// Final answer
fmt.Fprint(w, `{"choices":[{"message":{"content":"done"}}]}`)
}
}))
defer server.Close()
echoTool := &fakeTool{name: "echo", description: "echo", output: "ok"}
registry := tool.NewRegistry([]tool.Tool{echoTool})
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, registry, 10, "", nil, 0)
engine.SetToolEventHandler(eventHandler)
result, err := engine.Run(context.Background(), "do it")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if result != "done" {
t.Errorf("result = %q, want %q", result, "done")
}
// Must have exactly: tool_call → tool_result
if len(events) != 2 {
t.Fatalf("expected 2 events (tool_call, tool_result), got %d: %v", len(events), events)
}
if events[0] != "tool_call" {
t.Errorf("event[0] = %q, want 'tool_call'", events[0])
}
if events[1] != "tool_result" {
t.Errorf("event[1] = %q, want 'tool_result'", events[1])
}
if eventData[0] != "echo" {
t.Errorf("event[0] name = %q, want 'echo'", eventData[0])
}
if eventData[1] != "echo" {
t.Errorf("event[1] name = %q, want 'echo'", eventData[1])
}
}
func TestEngine_Run_CacheAccumulation(t *testing.T) {
// Server that returns cache metrics in usage, then final answer.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"choices":[{"message":{"content":"done"}}],"usage":{"prompt_tokens":100,"completion_tokens":20,"cache_creation_input_tokens":40,"cache_read_input_tokens":30}}`)
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
registry := tool.NewRegistry(nil)
engine := New(client, registry, 10, "", nil, 0)
result, err := engine.Run(context.Background(), "test")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if result != "done" {
t.Errorf("result = %q, want 'done'", result)
}
if engine.TotalCacheCreationTokens != 40 {
t.Errorf("TotalCacheCreationTokens = %d, want 40", engine.TotalCacheCreationTokens)
}
if engine.TotalCacheReadTokens != 30 {
t.Errorf("TotalCacheReadTokens = %d, want 30", engine.TotalCacheReadTokens)
}
if engine.TotalCachedTokens != 0 {
t.Errorf("TotalCachedTokens = %d, want 0", engine.TotalCachedTokens)
}
if engine.TotalInputTokens != 100 {
t.Errorf("TotalInputTokens = %d, want 100", engine.TotalInputTokens)
}
if engine.TotalOutputTokens != 20 {
t.Errorf("TotalOutputTokens = %d, want 20", engine.TotalOutputTokens)
}
}
func TestEngine_Run_CacheAccumulation_MultiIter(t *testing.T) {
// First call returns tool call + cache, second call returns answer + cache.
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
if callCount == 1 {
fmt.Fprint(w, `{"choices":[{"message":{"content":"thinking","tool_calls":[{"id":"c1","function":{"name":"echo","arguments":"{}"}}]}}],"usage":{"prompt_tokens":50,"completion_tokens":10,"cache_creation_input_tokens":20,"cache_read_input_tokens":15}}`)
} else {
fmt.Fprint(w, `{"choices":[{"message":{"content":"final"}}],"usage":{"prompt_tokens":30,"completion_tokens":5,"cache_creation_input_tokens":10,"cache_read_input_tokens":8}}`)
}
}))
defer server.Close()
echoTool := &fakeTool{name: "echo", description: "echoes", output: "ok"}
registry := tool.NewRegistry([]tool.Tool{echoTool})
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
engine := New(client, registry, 10, "", nil, 0)
result, err := engine.Run(context.Background(), "echo")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if result != "final" {
t.Errorf("result = %q, want 'final'", result)
}
// Cumulative: iter1 (20+15) + iter2 (10+8) = 30+23
if engine.TotalCacheCreationTokens != 30 {
t.Errorf("TotalCacheCreationTokens = %d, want 30", engine.TotalCacheCreationTokens)
}
if engine.TotalCacheReadTokens != 23 {
t.Errorf("TotalCacheReadTokens = %d, want 23", engine.TotalCacheReadTokens)
}
// Cumulative: iter1 (50+30) + iter2 (30+5) = 80+15
if engine.TotalInputTokens != 80 {
t.Errorf("TotalInputTokens = %d, want 80", engine.TotalInputTokens)
}
if engine.TotalOutputTokens != 15 {
t.Errorf("TotalOutputTokens = %d, want 15", engine.TotalOutputTokens)
}
if callCount != 2 {
t.Errorf("expected 2 LLM calls, got %d", callCount)
}
}
func TestEngine_Run_CacheAccumulation_OpenAI(t *testing.T) {
// OpenAI format: cached_tokens via prompt_tokens_details
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"choices":[{"message":{"content":"cached"}}],"usage":{"prompt_tokens":200,"completion_tokens":40,"prompt_tokens_details":{"cached_tokens":150}}}`)
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
registry := tool.NewRegistry(nil)
engine := New(client, registry, 10, "", nil, 0)
_, err := engine.Run(context.Background(), "test")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if engine.TotalCachedTokens != 150 {
t.Errorf("TotalCachedTokens = %d, want 150", engine.TotalCachedTokens)
}
if engine.TotalCacheCreationTokens != 0 {
t.Errorf("TotalCacheCreationTokens = %d, want 0", engine.TotalCacheCreationTokens)
}
if engine.TotalCacheReadTokens != 0 {
t.Errorf("TotalCacheReadTokens = %d, want 0", engine.TotalCacheReadTokens)
}
}
func TestEngine_Run_CacheAccumulation_NoCache(t *testing.T) {
// Cache accumulators should be zero when no cache metrics returned.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"choices":[{"message":{"content":"ok"}}],"usage":{"prompt_tokens":10,"completion_tokens":5}}`)
}))
defer server.Close()
client := llm.New(server.URL, "sk-test", "test-model", "", 0, 0)
registry := tool.NewRegistry(nil)
engine := New(client, registry, 10, "", nil, 0)
_, err := engine.Run(context.Background(), "test")
if err != nil {
t.Fatalf("Run() error: %v", err)
}
if engine.TotalCacheCreationTokens != 0 {
t.Errorf("TotalCacheCreationTokens = %d, want 0", engine.TotalCacheCreationTokens)
}
if engine.TotalCacheReadTokens != 0 {
t.Errorf("TotalCacheReadTokens = %d, want 0", engine.TotalCacheReadTokens)
}
if engine.TotalCachedTokens != 0 {
t.Errorf("TotalCachedTokens = %d, want 0", engine.TotalCachedTokens)
}
}
// ── Prompt Tiering Tests ───────────────────────────────────────────
// TestPromptTiering_SeparateMemoryMessage verifies that memory is injected
// as a separate system message rather than concatenated into messages[0].
// This ensures messages[0] (baseSystem) remains stable across turns for
// DeepSeek/Anthropic prompt caching.
func TestPromptTiering_SeparateMemoryMessage(t *testing.T) {
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
var body struct {
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
return
}
if callCount == 1 {
// Verify: messages[0] = baseSystem (stable), messages[1] = memory (volatile)
if len(body.Messages) < 2 {
t.Errorf("expected at least 2 messages (system + memory + user), got %d", len(body.Messages))
} else {
if body.Messages[0].Role != "system" {
t.Errorf("messages[0].Role = %q, want system", body.Messages[0].Role)
}
if body.Messages[0].Content != "You are a stable base." {
t.Errorf("messages[0].Content = %q, want %q", body.Messages[0].Content, "You are a stable base.")
}
if body.Messages[1].Role != "system" {
t.Errorf("messages[1].Role = %q, want system (memory)", body.Messages[1].Role)
}
if body.Messages[1].Content != "memory-block-v1" {
t.Errorf("messages[1].Content = %q, want memory-block-v1", body.Messages[1].Content)
}
}
// Return a tool call to force another iteration.
fmt.Fprint(w, `{"choices":[{"message":{"content":"","tool_calls":[{"id":"call_1","function":{"name":"echo","arguments":"{}"}}]}}]}`)
} else {
// Second call: memory should be updated.
if len(body.Messages) >= 2 && body.Messages[1].Role == "system" {
if body.Messages[1].Content != "memory-block-v2" {
t.Errorf("messages[1].Content = %q, want memory-block-v2", body.Messages[1].Content)
}
// messages[0] must still be the stable base.
if body.Messages[0].Content != "You are a stable base." {
t.Errorf("messages[0].Content changed: %q, want %q", body.Messages[0].Content, "You are a stable base.")