-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathagent.go
More file actions
1818 lines (1561 loc) · 46.4 KB
/
agent.go
File metadata and controls
1818 lines (1561 loc) · 46.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 agent
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/Protocol-Lattice/go-agent/src/memory"
"github.com/Protocol-Lattice/go-agent/src/models"
"github.com/alpkeskin/gotoon"
"github.com/universal-tool-calling-protocol/go-utcp"
"github.com/universal-tool-calling-protocol/go-utcp/src/plugins/chain"
"github.com/universal-tool-calling-protocol/go-utcp/src/plugins/codemode"
"github.com/universal-tool-calling-protocol/go-utcp/src/tools"
)
const (
defaultSystemPrompt = "You are the primary coordinator for an AI agent team. Provide concise, accurate answers and explain when you call tools or delegate work to specialist sub-agents."
defaultToolCacheTTL = 30 * time.Second
)
var (
roleUserRe = regexp.MustCompile(`(?mi)^(?:User|User\s*\(quoted\))\s*:`)
roleSystemRe = regexp.MustCompile(`(?mi)^(?:System|System\s*\(quoted\))\s*:`)
roleAssistantRe = regexp.MustCompile(`(?mi)^(?:Assistant|Assistant\s*\(quoted\))\s*:`)
roleMemoryRe = regexp.MustCompile(`(?mi)^Conversation memory`)
)
// Agent orchestrates model calls, memory, tools, and sub-agents.
type Agent struct {
model models.Agent
memory *memory.SessionMemory
systemPrompt string
contextLimit int
toolCatalog ToolCatalog
subAgentDirectory SubAgentDirectory
UTCPClient utcp.UtcpClientInterface
mu sync.Mutex
toolMu sync.RWMutex
toolSpecsCache []tools.Tool
toolSpecsExpiry time.Time
toolPromptCache string
toolPromptKey string
toolPromptExpiry time.Time
Shared *memory.SharedSession
CodeMode *codemode.CodeModeUTCP
CodeChain *chain.UtcpChainClient
AllowUnsafeTools bool
Guardrails *OutputGuardrails
}
// Options configure a new Agent.
type Options struct {
Model models.Agent
Memory *memory.SessionMemory
SystemPrompt string
ContextLimit int
Tools []Tool
SubAgents []SubAgent
ToolCatalog ToolCatalog
SubAgentDirectory SubAgentDirectory
UTCPClient utcp.UtcpClientInterface
CodeMode *codemode.CodeModeUTCP
Shared *memory.SharedSession
CodeChain *chain.UtcpChainClient
AllowUnsafeTools bool
Guardrails *OutputGuardrails
}
// New creates an Agent with the provided options.
func New(opts Options) (*Agent, error) {
if opts.Model == nil {
return nil, errors.New("agent requires a language model")
}
if opts.Memory == nil {
return nil, errors.New("agent requires session memory")
}
ctxLimit := opts.ContextLimit
if ctxLimit <= 0 {
ctxLimit = 8
}
systemPrompt := opts.SystemPrompt
if strings.TrimSpace(systemPrompt) == "" {
systemPrompt = defaultSystemPrompt
}
toolCatalog := opts.ToolCatalog
tolerantTools := false
if toolCatalog == nil {
toolCatalog = NewStaticToolCatalog(nil)
tolerantTools = true
}
for _, tool := range opts.Tools {
if tool == nil {
continue
}
if err := toolCatalog.Register(tool); err != nil {
if tolerantTools {
continue
}
return nil, err
}
}
subAgentDirectory := opts.SubAgentDirectory
tolerantSubAgents := false
if subAgentDirectory == nil {
subAgentDirectory = NewStaticSubAgentDirectory(nil)
tolerantSubAgents = true
}
for _, sa := range opts.SubAgents {
if sa == nil {
continue
}
if err := subAgentDirectory.Register(sa); err != nil {
if tolerantSubAgents {
continue
}
return nil, err
}
}
a := &Agent{
model: opts.Model,
memory: opts.Memory,
systemPrompt: systemPrompt,
contextLimit: ctxLimit,
toolCatalog: toolCatalog,
subAgentDirectory: subAgentDirectory,
UTCPClient: opts.UTCPClient,
Shared: opts.Shared,
CodeMode: opts.CodeMode,
CodeChain: opts.CodeChain,
AllowUnsafeTools: opts.AllowUnsafeTools,
Guardrails: opts.Guardrails,
}
return a, nil
}
// userLooksLikeToolCall returns true if the user *likely* meant to call a tool.
func (a *Agent) userLooksLikeToolCall(s string) bool {
s = strings.TrimSpace(strings.ToLower(s))
// Looks like: echo {...}
if strings.Contains(s, "{") && strings.Contains(s, "}") {
parts := strings.Fields(s)
if len(parts) > 0 {
tool := parts[0]
for _, t := range a.ToolSpecs() {
if strings.ToLower(t.Name) == tool {
return true
}
}
}
}
// Looks like: tool: echo {...}
if strings.HasPrefix(s, "tool:") {
return true
}
// Looks like: {"tool": "echo", ...}
if strings.HasPrefix(s, "{") && strings.Contains(s, "\"tool\"") {
return true
}
return false
}
func (a *Agent) decideIfToolsNeeded(
ctx context.Context,
query string,
tools string,
) (bool, error) {
prompt := fmt.Sprintf(`
Decide if the following user query requires using ANY UTCP tools.
USER QUERY:
%q
AVAILABLE UTCP TOOLS:
%s
Respond ONLY in JSON:
{ "needs": true } or { "needs": false }
`, query, tools)
raw, err := a.model.Generate(ctx, prompt)
if err != nil {
return false, err
}
jsonStr := extractJSON(fmt.Sprint(raw))
if jsonStr == "" {
return false, nil
}
var resp struct {
Needs bool `json:"needs"`
}
if err := json.Unmarshal([]byte(jsonStr), &resp); err != nil {
return false, nil
}
return resp.Needs, nil
}
func (a *Agent) selectTools(
ctx context.Context,
query string,
tools string,
) ([]string, error) {
prompt := fmt.Sprintf(`
Select ALL UTCP tools that match the user's intent.
USER QUERY:
%q
AVAILABLE UTCP TOOLS:
%s
Respond ONLY in JSON:
{
"tools": ["provider.tool", ...]
}
Rules:
- Use ONLY names listed above.
- NO modifications, NO guessing.
- If multiple tools apply, include all.
`, query, tools)
raw, err := a.model.Generate(ctx, prompt)
if err != nil {
return nil, err
}
jsonStr := extractJSON(fmt.Sprint(raw))
if jsonStr == "" {
return nil, nil
}
var resp struct {
Tools []string `json:"tools"`
}
_ = json.Unmarshal([]byte(jsonStr), &resp)
return resp.Tools, nil
}
// Flush persists session memory into the long-term store.
func (a *Agent) Flush(ctx context.Context, sessionID string) error {
return a.memory.FlushToLongTerm(ctx, sessionID)
}
// Checkpoint serializes the agent's current state (system prompt and short-term memory)
// to a byte slice. This can be saved to disk or a database to pause the agent.
func (a *Agent) Checkpoint() ([]byte, error) {
a.mu.Lock()
defer a.mu.Unlock()
state := AgentState{
SystemPrompt: a.systemPrompt,
ShortTerm: a.memory.ExportShortTerm(),
Timestamp: time.Now(),
}
if a.Shared != nil {
state.JoinedSpaces = a.Shared.ExportJoinedSpaces()
}
return json.Marshal(state)
}
// Restore rehydrates the agent's state from a checkpoint.
// It restores the system prompt and short-term memory.
func (a *Agent) Restore(data []byte) error {
a.mu.Lock()
defer a.mu.Unlock()
var state AgentState
if err := json.Unmarshal(data, &state); err != nil {
return err
}
a.systemPrompt = state.SystemPrompt
a.memory.ImportShortTerm(state.ShortTerm)
if a.Shared != nil && len(state.JoinedSpaces) > 0 {
a.Shared.ImportJoinedSpaces(state.JoinedSpaces)
}
return nil
}
func (a *Agent) executeTool(
ctx context.Context,
sessionID, toolName string,
args map[string]any,
) (any, error) {
if args == nil {
args = map[string]any{}
}
// ---------------------------------------------
// 1. REMOTE UTCP TOOL
// If "stream": true → CallToolStream
// else → CallTool
// ---------------------------------------------
if a.UTCPClient != nil {
// streaming request?
if streamFlag, ok := args["stream"].(bool); ok && streamFlag {
stream, err := a.UTCPClient.CallToolStream(ctx, toolName, args)
if err != nil {
return nil, err
}
if stream == nil {
return nil, fmt.Errorf("CallToolStream returned nil stream for %s", toolName)
}
// Accumulate streamed chunks into a single string
var sb strings.Builder
for {
chunk, err := stream.Next()
if err != nil {
break
}
if chunk != nil {
sb.WriteString(fmt.Sprint(chunk))
}
}
return sb.String(), nil
}
// Non-streaming remote call
return a.UTCPClient.CallTool(ctx, toolName, args)
}
// ---------------------------------------------
// 3. Unknown tool
// ---------------------------------------------
return nil, fmt.Errorf("unknown tool: %s", toolName)
}
// buildPrompt assembles the full assistant prompt for normal LLM generation.
// It does NOT include Toon markup. It NEVER formats for tool calls.
// It simply injects system prompt, retrieved memory, and file context.
func (a *Agent) buildPrompt(
ctx context.Context,
sessionID string,
userInput string,
) (string, error) {
// Detect query type to choose retrieval depth.
queryType := classifyQuery(userInput)
var records []memory.MemoryRecord
var err error
switch queryType {
case QueryMath:
// Skip heavy retrieval; math needs no context.
case QueryShortFactoid:
records, err = a.retrieveContext(ctx, sessionID, userInput, min(a.contextLimit/2, 3))
if err != nil {
return "", fmt.Errorf("retrieve context: %w", err)
}
case QueryComplex:
records, err = a.retrieveContext(ctx, sessionID, userInput, a.contextLimit)
if err != nil {
return "", fmt.Errorf("retrieve context: %w", err)
}
default:
// Unknown → no retrieval
}
// Build LLM prompt without tools/subagents:
// Tools are only exposed inside the toolOrchestrator,
// not during normal generation.
var sb strings.Builder
sb.Grow(4096)
sb.WriteString(a.systemPrompt)
sb.WriteString("\n\nConversation memory (TOON):\n")
sb.WriteString(a.renderMemory(records))
sb.WriteString("\n\nUser: ")
sb.WriteString(sanitizeInput(userInput))
sb.WriteString("\n\n") // no forced persona label
// Rehydrate attachments
files, _ := a.RetrieveAttachmentFiles(ctx, sessionID, a.contextLimit)
if len(files) > 0 {
sb.WriteString(a.buildAttachmentPrompt("Session attachments (rehydrated)", files))
}
return sb.String(), nil
}
// renderMemory formats retrieved memory records into a clean, token-efficient list.
func (a *Agent) renderMemory(records []memory.MemoryRecord) string {
if len(records) == 0 {
return "(no stored memory)\n"
}
entries := make([]map[string]any, 0, len(records))
var fallback strings.Builder
counter := 0
for _, rec := range records {
content := strings.TrimSpace(rec.Content)
if content == "" {
continue
}
counter++
role := metadataRole(rec.Metadata)
space := rec.Space
if space == "" {
space = rec.SessionID
}
entry := map[string]any{
"id": counter,
"role": role,
"space": space,
"score": rec.Score,
"importance": rec.Importance,
"source": rec.Source,
"summary": rec.Summary,
"content": content,
"last_update": rec.LastEmbedded.UTC().Format(time.RFC3339Nano),
}
if rec.LastEmbedded.IsZero() {
delete(entry, "last_update")
}
entries = append(entries, entry)
fallback.WriteString(fmt.Sprintf("%d. [%s] %s\n", counter, role, escapePromptContent(content)))
}
if len(entries) == 0 {
return "(no stored memory)\n"
}
if toon := encodeTOONBlock(map[string]any{"memories": entries}); toon != "" {
return toon + "\n"
}
return fallback.String()
}
func escapePromptContent(s string) string {
s = strings.ReplaceAll(s, "`", "'")
s = roleUserRe.ReplaceAllString(s, "User (quoted):")
s = roleSystemRe.ReplaceAllString(s, "System (quoted):")
s = roleAssistantRe.ReplaceAllString(s, "Assistant (quoted):")
s = roleMemoryRe.ReplaceAllString(s, "Conversation memory (quoted):")
return s
}
func sanitizeInput(s string) string {
s = strings.TrimSpace(s)
s = roleUserRe.ReplaceAllString(s, "User (quoted):")
s = roleSystemRe.ReplaceAllString(s, "System (quoted):")
s = roleAssistantRe.ReplaceAllString(s, "Assistant (quoted):")
s = roleMemoryRe.ReplaceAllString(s, "Conversation memory (quoted):")
return s
}
func (a *Agent) detectDirectToolCall(s string) (string, map[string]any, bool) {
s = strings.TrimSpace(s)
lower := strings.ToLower(s)
// Build a lowercase lookup of all registered tool names
valid := make(map[string]string) // lowerName → exactName
prefixes := make(map[string]struct{}) // provider prefixes
bases := make(map[string][]string) // short name → list of full names
for _, spec := range a.ToolSpecs() {
exact := spec.Name
lowerName := strings.ToLower(exact)
valid[lowerName] = exact
// Collect prefix (provider)
if parts := strings.Split(lowerName, "."); len(parts) >= 2 {
prefixes[parts[0]] = struct{}{}
short := parts[len(parts)-1]
bases[short] = append(bases[short], exact)
}
}
// helper: try matching tool name dynamically using full registry
normalize := func(name string) (string, bool) {
nameLower := strings.ToLower(strings.TrimSpace(name))
// 1) Exact match
if exact, ok := valid[nameLower]; ok {
return exact, true
}
// 2) Match by fully-qualified suffix (e.g. "math.add")
for fullLower, exact := range valid {
if strings.HasSuffix(fullLower, "."+nameLower) {
return exact, true
}
}
// 3) Match by base (last segment only)
if list, ok := bases[nameLower]; ok && len(list) > 0 {
// if multiple tools share the same short name, choose the first or return false
return list[0], true
}
return "", false
}
// ---------------------------------------------------------
// Case 1: Raw JSON {"tool":"...", "arguments":{...}}
// ---------------------------------------------------------
if strings.HasPrefix(s, "{") && strings.Contains(s, "\"tool\"") {
var payload struct {
Tool string `json:"tool"`
Arguments map[string]any `json:"arguments"`
}
if err := json.Unmarshal([]byte(s), &payload); err == nil && payload.Tool != "" {
if real, ok := normalize(payload.Tool); ok {
return real, payload.Arguments, ok
}
return "", nil, false
}
}
// ---------------------------------------------------------
// Case 2: DSL: tool: echo { ... }
// ---------------------------------------------------------
if strings.HasPrefix(lower, "tool:") {
rest := strings.TrimSpace(s[len("tool:"):])
parts := strings.Fields(rest)
if len(parts) >= 2 {
tool := parts[0]
argsStr := strings.TrimSpace(rest[len(tool):])
var args map[string]any
_ = json.Unmarshal([]byte(argsStr), &args)
if real, ok := normalize(tool); ok {
return real, args, ok
}
return "", nil, false
}
}
// ---------------------------------------------------------
// Case 3: Shorthand: echo { ... }
// ---------------------------------------------------------
parts := strings.Fields(s)
if len(parts) >= 2 {
tool := strings.TrimSpace(parts[0])
argsStr := strings.TrimSpace(s[len(tool):])
var args map[string]any
if err := json.Unmarshal([]byte(argsStr), &args); err == nil {
if real, ok := normalize(tool); ok {
return real, args, ok
}
return "", nil, false
}
}
return "", nil, false
}
func (a *Agent) handleCommand(ctx context.Context, sessionID, userInput string) (bool, string, map[string]string, error) {
trimmed := strings.TrimSpace(userInput)
lower := strings.ToLower(trimmed)
switch {
case strings.HasPrefix(lower, "subagent:"):
payload := strings.TrimSpace(trimmed[len("subagent:"):])
if payload == "" {
return true, "", nil, errors.New("subagent name is missing")
}
name, args := splitCommand(payload)
sa, ok := a.lookupSubAgent(name)
if !ok {
return true, "", nil, fmt.Errorf("unknown subagent: %s", name)
}
result, err := sa.Run(ctx, args)
if err != nil {
return true, "", nil, err
}
meta := map[string]string{"subagent": sa.Name()}
a.storeMemory(sessionID, "subagent", fmt.Sprintf("%s => %s", sa.Name(), strings.TrimSpace(result)), meta)
return true, result, meta, nil
default:
return false, "", nil, nil
}
}
func parseToolArguments(raw string) map[string]any {
raw = strings.TrimSpace(raw)
if raw == "" {
return map[string]any{}
}
var payload map[string]any
if strings.HasPrefix(raw, "{") {
if err := json.Unmarshal([]byte(raw), &payload); err == nil {
return payload
}
}
if strings.HasPrefix(raw, "[") {
var arr []any
if err := json.Unmarshal([]byte(raw), &arr); err == nil {
return map[string]any{"items": arr}
}
}
return map[string]any{"input": raw}
}
func (a *Agent) storeMemory(sessionID, role, content string, extra map[string]string) {
if a == nil || strings.TrimSpace(content) == "" {
return
}
// Build metadata safely.
meta := map[string]string{}
if rs := strings.TrimSpace(role); rs != "" {
meta["role"] = rs
}
if extra != nil {
for k, v := range extra {
ks, vs := strings.TrimSpace(k), strings.TrimSpace(v)
if ks != "" && vs != "" {
meta[ks] = vs
}
}
}
// Snapshot pointers without holding the lock during external calls.
a.mu.Lock()
shared := a.Shared
mem := a.memory
a.mu.Unlock()
// 1) Best-effort write to shared spaces (doesn't require embedder).
if shared != nil {
shared.AddShortLocal(content, meta)
for _, space := range shared.Spaces() {
_ = shared.AddShortTo(space, content, meta) // ignore per-space errors
}
}
// 2) Write to session memory if available.
if mem == nil || mem.Embedder == nil {
return // nothing else to do; avoid panic
}
// Compute embedding with a small timeout to avoid hanging the call.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
embedding, err := mem.Embedder.Embed(ctx, content)
if err != nil {
return // silent drop on embed failure; consider logging if desired
}
metaBytes, _ := json.Marshal(meta)
// Append to short-term memory under lock.
a.mu.Lock()
defer a.mu.Unlock()
mem.AddShortTerm(sessionID, content, string(metaBytes), embedding)
}
func (a *Agent) storeAttachmentMemories(sessionID string, files []models.File) {
for i, file := range files {
name := strings.TrimSpace(file.Name)
if name == "" {
name = fmt.Sprintf("file_%d", i+1)
}
mime := strings.TrimSpace(file.MIME)
content := buildAttachmentMemoryContent(name, mime, file.Data)
extra := map[string]string{
"source": "file_upload",
"filename": name,
}
if mime != "" {
extra["mime"] = mime
}
if size := len(file.Data); size > 0 {
extra["size_bytes"] = strconv.Itoa(size)
}
if len(file.Data) > 0 {
extra["data_base64"] = base64.StdEncoding.EncodeToString(file.Data)
}
if isTextAttachment(mime, file.Data) {
extra["text"] = "true"
} else {
extra["text"] = "false"
}
a.storeMemory(sessionID, "attachment", content, extra)
}
}
// RetrieveAttachmentFiles returns attachment files stored for the session.
// It reconstructs the original bytes from base64-encoded metadata, making it
// suitable for binary assets such as images and videos.
func (a *Agent) RetrieveAttachmentFiles(ctx context.Context, sessionID string, limit int) ([]models.File, error) {
if a == nil || a.memory == nil {
return nil, nil
}
if limit <= 0 {
limit = a.contextLimit
if limit <= 0 {
limit = 8
}
}
records, err := a.memory.RetrieveContext(ctx, sessionID, "", limit)
if err != nil {
return nil, err
}
var attachments []models.File
for _, record := range records {
if metadataRole(record.Metadata) != "attachment" {
continue
}
file, ok := attachmentFromRecord(record)
if !ok {
continue
}
attachments = append(attachments, file)
}
return attachments, nil
}
func attachmentFromRecord(record memory.MemoryRecord) (models.File, bool) {
if strings.TrimSpace(record.Metadata) == "" {
return models.File{}, false
}
var payload map[string]any
if err := json.Unmarshal([]byte(record.Metadata), &payload); err != nil {
return models.File{}, false
}
name, _ := payload["filename"].(string)
mime, _ := payload["mime"].(string)
dataB64, _ := payload["data_base64"].(string)
if name == "" {
name = "attachment"
}
var data []byte
if dataB64 != "" {
raw, err := base64.StdEncoding.DecodeString(dataB64)
if err != nil {
return models.File{}, false
}
data = raw
} else {
data = extractTextAttachment(record.Content)
}
return models.File{Name: name, MIME: mime, Data: data}, true
}
func extractTextAttachment(content string) []byte {
idx := strings.Index(content, ":\n")
if idx == -1 {
return nil
}
return []byte(content[idx+2:])
}
func isTextAttachment(mime string, data []byte) bool {
mt := strings.ToLower(strings.TrimSpace(mime))
switch {
case strings.HasPrefix(mt, "text/"):
return true
case mt == "application/json",
mt == "application/xml",
mt == "application/x-yaml",
mt == "application/yaml",
mt == "text/markdown",
mt == "text/x-markdown":
return true
}
if len(data) == 0 {
return true
}
return utf8.Valid(data)
}
func toolCacheTTL() time.Duration {
raw := strings.TrimSpace(os.Getenv("utcp_tool_cache_ttl_ms"))
if raw == "" {
return defaultToolCacheTTL
}
ms, err := strconv.Atoi(raw)
if err != nil || ms <= 0 {
return defaultToolCacheTTL
}
return time.Duration(ms) * time.Millisecond
}
func toolListSignature(specs []tools.Tool) string {
if len(specs) == 0 {
return ""
}
var sb strings.Builder
sb.Grow(len(specs) * 32)
for _, t := range specs {
sb.WriteString(strings.ToLower(strings.TrimSpace(t.Name)))
sb.WriteByte('|')
sb.WriteString(strings.TrimSpace(t.Description))
sb.WriteByte('|')
sb.WriteString(strconv.Itoa(len(t.Inputs.Properties)))
sb.WriteByte('|')
sb.WriteString(strconv.Itoa(len(t.Inputs.Required)))
sb.WriteByte(';')
}
return sb.String()
}
func (a *Agent) cachedToolPrompt(specs []tools.Tool) string {
if len(specs) == 0 {
return ""
}
key := toolListSignature(specs)
now := time.Now()
a.toolMu.RLock()
prompt := a.toolPromptCache
cacheKey := a.toolPromptKey
promptExpiry := a.toolPromptExpiry
specExpiry := a.toolSpecsExpiry
a.toolMu.RUnlock()
if prompt != "" && key == cacheKey && (promptExpiry.IsZero() || now.Before(promptExpiry)) {
return prompt
}
rendered := renderUtcpToolsForPrompt(specs)
expiry := specExpiry
if expiry.IsZero() || now.After(expiry) {
expiry = now.Add(toolCacheTTL())
}
a.toolMu.Lock()
a.toolPromptCache = rendered
a.toolPromptKey = key
a.toolPromptExpiry = expiry
a.toolMu.Unlock()
return rendered
}
func renderUtcpToolsForPrompt(specs []tools.Tool) string {
var sb strings.Builder
sb.WriteString("------------------------------------------------------------\n")
sb.WriteString("UTCP TOOL REFERENCE (INPUT + OUTPUT SCHEMAS)\n")
sb.WriteString("Use EXACT field names listed below. Do NOT invent new keys.\n")
sb.WriteString("------------------------------------------------------------\n\n")
for _, t := range specs {
sb.WriteString(fmt.Sprintf("TOOL: %s\n", t.Name))
sb.WriteString(fmt.Sprintf("DESCRIPTION: %s\n\n", t.Description))
// -------------------------------
// INPUT FIELD LIST
// -------------------------------
sb.WriteString("INPUT FIELDS (USE EXACTLY THESE KEYS):\n")
if len(t.Inputs.Properties) == 0 {
sb.WriteString("- (no fields)\n")
} else {
for key, raw := range t.Inputs.Properties {
// Try to extract "type" from nested schema if present
propType := "any"
if m, ok := raw.(map[string]any); ok {
if v, ok := m["type"]; ok {
if s, ok := v.(string); ok {
propType = s
}
}
}
sb.WriteString(fmt.Sprintf("- %s: %s\n", key, propType))
}
}
// Required field list
if len(t.Inputs.Required) > 0 {
sb.WriteString("\nREQUIRED FIELDS:\n")
for _, r := range t.Inputs.Required {
sb.WriteString(fmt.Sprintf("- %s\n", r))
}
}
sb.WriteString("\n")
// Full JSON schema for LLM clarity
inBytes, _ := json.MarshalIndent(t.Inputs, "", " ")
sb.WriteString("FULL INPUT SCHEMA (JSON):\n")
sb.WriteString(string(inBytes))
sb.WriteString("\n\n")
// -------------------------------
// OUTPUT SCHEMA
// -------------------------------
sb.WriteString("OUTPUT SCHEMA (EXACT SHAPE RETURNED BY TOOL):\n")
if t.Outputs.Type != "" || len(t.Outputs.Properties) > 0 {
outBytes, _ := json.MarshalIndent(t.Outputs, "", " ")
sb.WriteString(string(outBytes))
} else {
// Generic fallback
sb.WriteString("{ \"result\": <any> }\n")
}
sb.WriteString("\n")
sb.WriteString("------------------------------------------------------------\n\n")
}
return sb.String()
}
func buildAttachmentMemoryContent(name, mime string, data []byte) string {
display := strings.TrimSpace(name)
if display == "" {
display = "attachment"
}
descriptor := display
if m := strings.TrimSpace(mime); m != "" {
descriptor = fmt.Sprintf("%s (%s)", display, m)
}
if len(data) == 0 {
return fmt.Sprintf("Attachment %s [empty file]", descriptor)
}
if isTextAttachment(mime, data) {
var sb strings.Builder
sb.Grow(len(data) + len(descriptor) + 32)
sb.WriteString("Attachment ")
sb.WriteString(descriptor)
sb.WriteString(":\n")
sb.Write(data)
return sb.String()
}
return fmt.Sprintf("Attachment %s [%d bytes of non-text content]", descriptor, len(data))
}
func (a *Agent) lookupTool(name string) (Tool, ToolSpec, bool) {
if a.toolCatalog == nil {
return nil, ToolSpec{}, false
}
return a.toolCatalog.Lookup(name)
}
func (a *Agent) lookupSubAgent(name string) (SubAgent, bool) {
if a.subAgentDirectory == nil {
return nil, false
}
return a.subAgentDirectory.Lookup(name)
}
// ToolSpecs returns the registered tool specifications in deterministic order.
func (a *Agent) ToolSpecs() []tools.Tool {
now := time.Now()
a.toolMu.RLock()