forked from docker/docker-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.go
More file actions
1978 lines (1700 loc) · 68.8 KB
/
runtime.go
File metadata and controls
1978 lines (1700 loc) · 68.8 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 runtime
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"github.com/docker/cagent/pkg/agent"
"github.com/docker/cagent/pkg/chat"
"github.com/docker/cagent/pkg/config/latest"
"github.com/docker/cagent/pkg/config/types"
"github.com/docker/cagent/pkg/hooks"
"github.com/docker/cagent/pkg/model/provider"
"github.com/docker/cagent/pkg/model/provider/options"
"github.com/docker/cagent/pkg/modelsdev"
"github.com/docker/cagent/pkg/permissions"
"github.com/docker/cagent/pkg/rag"
ragtypes "github.com/docker/cagent/pkg/rag/types"
"github.com/docker/cagent/pkg/session"
"github.com/docker/cagent/pkg/sessiontitle"
"github.com/docker/cagent/pkg/team"
"github.com/docker/cagent/pkg/telemetry"
"github.com/docker/cagent/pkg/tools"
"github.com/docker/cagent/pkg/tools/builtin"
mcptools "github.com/docker/cagent/pkg/tools/mcp"
)
type ResumeType string
// ElicitationResult represents the result of an elicitation request
type ElicitationResult struct {
Action tools.ElicitationAction
Content map[string]any // The submitted form data (only present when action is "accept")
}
// ElicitationError represents an error from a declined/cancelled elicitation
type ElicitationError struct {
Action string
Message string
}
func (e *ElicitationError) Error() string {
return fmt.Sprintf("elicitation %s: %s", e.Action, e.Message)
}
const (
ResumeTypeApprove ResumeType = "approve"
ResumeTypeApproveSession ResumeType = "approve-session"
ResumeTypeApproveTool ResumeType = "approve-tool"
ResumeTypeReject ResumeType = "reject"
)
// ResumeRequest carries the user's confirmation decision along with an optional
// reason (used when rejecting a tool call to help the model understand why).
type ResumeRequest struct {
Type ResumeType
Reason string // Optional; primarily used with ResumeTypeReject
ToolName string // Optional; used with ResumeTypeApproveTool to specify which tool to always allow
}
// ResumeApprove creates a ResumeRequest to approve a single tool call.
func ResumeApprove() ResumeRequest {
return ResumeRequest{Type: ResumeTypeApprove}
}
// ResumeApproveSession creates a ResumeRequest to approve all tool calls for the session.
func ResumeApproveSession() ResumeRequest {
return ResumeRequest{Type: ResumeTypeApproveSession}
}
// ResumeApproveTool creates a ResumeRequest to always approve a specific tool for the session.
func ResumeApproveTool(toolName string) ResumeRequest {
return ResumeRequest{Type: ResumeTypeApproveTool, ToolName: toolName}
}
// ResumeReject creates a ResumeRequest to reject a tool call with an optional reason.
func ResumeReject(reason string) ResumeRequest {
return ResumeRequest{Type: ResumeTypeReject, Reason: reason}
}
// ToolHandlerFunc is a function type for handling tool calls
type ToolHandlerFunc func(ctx context.Context, sess *session.Session, toolCall tools.ToolCall, events chan Event) (*tools.ToolCallResult, error)
type ToolHandler struct {
handler ToolHandlerFunc
tool tools.Tool
}
// ElicitationRequestHandler is a function type for handling elicitation requests
type ElicitationRequestHandler func(ctx context.Context, message string, schema map[string]any) (map[string]any, error)
// Runtime defines the contract for runtime execution
type Runtime interface {
// CurrentAgentInfo returns information about the currently active agent
CurrentAgentInfo(ctx context.Context) CurrentAgentInfo
// CurrentAgentName returns the name of the currently active agent
CurrentAgentName() string
// SetCurrentAgent sets the currently active agent for subsequent user messages
SetCurrentAgent(agentName string) error
// CurrentAgentTools returns the tools for the active agent
CurrentAgentTools(ctx context.Context) ([]tools.Tool, error)
// EmitStartupInfo emits initial agent, team, and toolset information for immediate display
EmitStartupInfo(ctx context.Context, events chan Event)
// ResetStartupInfo resets the startup info emission flag, allowing re-emission
ResetStartupInfo()
// RunStream starts the agent's interaction loop and returns a channel of events
RunStream(ctx context.Context, sess *session.Session) <-chan Event
// Run starts the agent's interaction loop and returns the final messages
Run(ctx context.Context, sess *session.Session) ([]session.Message, error)
// Resume allows resuming execution after user confirmation.
// The ResumeRequest carries the decision type and an optional reason (for rejections).
Resume(ctx context.Context, req ResumeRequest)
// ResumeElicitation sends an elicitation response back to a waiting elicitation request
ResumeElicitation(_ context.Context, action tools.ElicitationAction, content map[string]any) error
// SessionStore returns the session store for browsing/loading past sessions.
// Returns nil if no persistent session store is configured.
SessionStore() session.Store
// Summarize generates a summary for the session
Summarize(ctx context.Context, sess *session.Session, additionalPrompt string, events chan Event)
// PermissionsInfo returns the team-level permission patterns (allow/deny).
// Returns nil if no permissions are configured.
PermissionsInfo() *PermissionsInfo
// CurrentAgentSkillsEnabled returns whether skills are enabled for the current agent.
CurrentAgentSkillsEnabled() bool
// CurrentMCPPrompts returns MCP prompts available from the current agent's toolsets.
// Returns an empty map if no MCP prompts are available.
CurrentMCPPrompts(ctx context.Context) map[string]mcptools.PromptInfo
// ExecuteMCPPrompt executes a named MCP prompt with the given arguments.
ExecuteMCPPrompt(ctx context.Context, promptName string, arguments map[string]string) (string, error)
// UpdateSessionTitle persists a new title for the current session.
UpdateSessionTitle(ctx context.Context, sess *session.Session, title string) error
// TitleGenerator returns a generator for automatic session titles, or nil
// if the runtime does not support local title generation (e.g. remote runtimes).
TitleGenerator() *sessiontitle.Generator
}
// PermissionsInfo contains the allow and deny patterns for tool permissions.
type PermissionsInfo struct {
Allow []string
Deny []string
}
type CurrentAgentInfo struct {
Name string
Description string
Commands types.Commands
}
type ModelStore interface {
GetModel(ctx context.Context, modelID string) (*modelsdev.Model, error)
}
// RAGInitializer is implemented by runtimes that support background RAG initialization.
// Local runtimes use this to start indexing early; remote runtimes typically do not.
type RAGInitializer interface {
StartBackgroundRAGInit(ctx context.Context, sendEvent func(Event))
}
// LocalRuntime manages the execution of agents
type LocalRuntime struct {
toolMap map[string]ToolHandler
team *team.Team
currentAgent string
resumeChan chan ResumeRequest
tracer trace.Tracer
modelsStore ModelStore
sessionCompaction bool
managedOAuth bool
startupInfoEmitted bool // Track if startup info has been emitted to avoid unnecessary duplication
elicitationRequestCh chan ElicitationResult // Channel for receiving elicitation responses
elicitationEventsChannel chan Event // Current events channel for sending elicitation requests
elicitationEventsChannelMux sync.RWMutex // Protects elicitationEventsChannel
ragInitialized atomic.Bool
sessionCompactor *sessionCompactor
sessionStore session.Store
workingDir string // Working directory for hooks execution
env []string // Environment variables for hooks execution
modelSwitcherCfg *ModelSwitcherConfig
// fallbackCooldowns tracks per-agent cooldown state for sticky fallback behavior
fallbackCooldowns map[string]*fallbackCooldownState
fallbackCooldownsMux sync.RWMutex
}
type streamResult struct {
Calls []tools.ToolCall
Content string
ReasoningContent string
ThinkingSignature string // Used with Anthropic's extended thinking feature
ThoughtSignature []byte
Stopped bool
ActualModel string // The actual model used (may differ from configured model with routing)
Usage *chat.Usage // Token usage for this stream
RateLimit *chat.RateLimit
}
type Opt func(*LocalRuntime)
func WithCurrentAgent(agentName string) Opt {
return func(r *LocalRuntime) {
r.currentAgent = agentName
}
}
func WithManagedOAuth(managed bool) Opt {
return func(r *LocalRuntime) {
r.managedOAuth = managed
}
}
// WithTracer sets a custom OpenTelemetry tracer; if not provided, tracing is disabled (no-op).
func WithTracer(t trace.Tracer) Opt {
return func(r *LocalRuntime) {
r.tracer = t
}
}
func WithSessionCompaction(sessionCompaction bool) Opt {
return func(r *LocalRuntime) {
r.sessionCompaction = sessionCompaction
}
}
func WithModelStore(store ModelStore) Opt {
return func(r *LocalRuntime) {
r.modelsStore = store
}
}
func WithSessionStore(store session.Store) Opt {
return func(r *LocalRuntime) {
r.sessionStore = store
}
}
// WithWorkingDir sets the working directory for hooks execution
func WithWorkingDir(dir string) Opt {
return func(r *LocalRuntime) {
r.workingDir = dir
}
}
// WithEnv sets the environment variables for hooks execution
func WithEnv(env []string) Opt {
return func(r *LocalRuntime) {
r.env = env
}
}
// NewLocalRuntime creates a new LocalRuntime without the persistence wrapper.
// This is useful for testing or when persistence is handled externally.
func NewLocalRuntime(agents *team.Team, opts ...Opt) (*LocalRuntime, error) {
defaultAgent, err := agents.DefaultAgent()
if err != nil {
return nil, err
}
r := &LocalRuntime{
toolMap: make(map[string]ToolHandler),
team: agents,
currentAgent: defaultAgent.Name(),
resumeChan: make(chan ResumeRequest),
elicitationRequestCh: make(chan ElicitationResult),
sessionCompaction: true,
managedOAuth: true,
sessionStore: session.NewInMemorySessionStore(),
fallbackCooldowns: make(map[string]*fallbackCooldownState),
}
for _, opt := range opts {
opt(r)
}
if r.modelsStore == nil {
modelsStore, err := modelsdev.NewStore()
if err != nil {
return nil, err
}
r.modelsStore = modelsStore
}
// Validate that the current agent exists and has a model
// (currentAgent might have been changed by options)
defaultAgent, err = r.team.Agent(r.currentAgent)
if err != nil {
return nil, err
}
model := defaultAgent.Model()
if model == nil {
return nil, fmt.Errorf("agent %s has no valid model", defaultAgent.Name())
}
r.sessionCompactor = newSessionCompactor(model, r.sessionStore)
slog.Debug("Creating new runtime", "agent", r.currentAgent, "available_agents", agents.Size())
return r, nil
}
// StartBackgroundRAGInit initializes RAG in background and forwards events
// Should be called early (e.g., by App) to start indexing before RunStream
func (r *LocalRuntime) StartBackgroundRAGInit(ctx context.Context, sendEvent func(Event)) {
if r.ragInitialized.Swap(true) {
return
}
ragManagers := r.team.RAGManagers()
if len(ragManagers) == 0 {
return
}
slog.Debug("Starting background RAG initialization with event forwarding", "manager_count", len(ragManagers))
// Set up event forwarding BEFORE starting initialization
// This ensures all events are captured
r.forwardRAGEvents(ctx, ragManagers, sendEvent)
// Now start initialization (events will be forwarded)
r.team.InitializeRAG(ctx)
r.team.StartRAGFileWatchers(ctx)
}
// forwardRAGEvents forwards RAG manager events to the given callback
// Consolidates duplicated event forwarding logic
func (r *LocalRuntime) forwardRAGEvents(ctx context.Context, ragManagers map[string]*rag.Manager, sendEvent func(Event)) {
for _, mgr := range ragManagers {
go func(mgr *rag.Manager) {
ragName := mgr.Name()
slog.Debug("Starting RAG event forwarder goroutine", "rag", ragName)
for {
select {
case <-ctx.Done():
slog.Debug("RAG event forwarder stopped", "rag", ragName)
return
case ragEvent, ok := <-mgr.Events():
if !ok {
slog.Debug("RAG events channel closed", "rag", ragName)
return
}
agentName := r.currentAgent
slog.Debug("Forwarding RAG event", "type", ragEvent.Type, "rag", ragName, "agent", agentName)
switch ragEvent.Type {
case ragtypes.EventTypeIndexingStarted:
sendEvent(RAGIndexingStarted(ragName, ragEvent.StrategyName, agentName))
case ragtypes.EventTypeIndexingProgress:
if ragEvent.Progress != nil {
sendEvent(RAGIndexingProgress(ragName, ragEvent.StrategyName, ragEvent.Progress.Current, ragEvent.Progress.Total, agentName))
}
case ragtypes.EventTypeIndexingComplete:
sendEvent(RAGIndexingCompleted(ragName, ragEvent.StrategyName, agentName))
case ragtypes.EventTypeUsage:
// Convert RAG usage to TokenUsageEvent so TUI displays it
sendEvent(TokenUsage(
"",
agentName,
ragEvent.TotalTokens, // input tokens (embeddings)
0, // output tokens (0 for embeddings)
ragEvent.TotalTokens, // context length
0, // context limit (not applicable)
ragEvent.Cost,
))
case ragtypes.EventTypeError:
if ragEvent.Error != nil {
sendEvent(Error(fmt.Sprintf("RAG %s error: %v", ragName, ragEvent.Error)))
}
default:
// Log unhandled events for debugging
slog.Debug("Unhandled RAG event type", "type", ragEvent.Type, "rag", ragName)
}
}
}
}(mgr)
}
}
// InitializeRAG is called within RunStream as a fallback when background init wasn't used
// (e.g., for exec command or API mode where there's no App)
func (r *LocalRuntime) InitializeRAG(ctx context.Context, events chan Event) {
// If already initialized via StartBackgroundRAGInit, skip entirely
// Event forwarding was already set up there
if r.ragInitialized.Swap(true) {
slog.Debug("RAG already initialized, event forwarding already active", "manager_count", len(r.team.RAGManagers()))
return
}
ragManagers := r.team.RAGManagers()
if len(ragManagers) == 0 {
return
}
slog.Debug("Setting up RAG initialization (fallback path for non-TUI)", "manager_count", len(ragManagers))
// Set up event forwarding BEFORE starting initialization
r.forwardRAGEvents(ctx, ragManagers, func(event Event) {
events <- event
})
// Start initialization and file watchers
r.team.InitializeRAG(ctx)
r.team.StartRAGFileWatchers(ctx)
}
func (r *LocalRuntime) CurrentAgentName() string {
return r.currentAgent
}
func (r *LocalRuntime) CurrentAgentInfo(context.Context) CurrentAgentInfo {
currentAgent := r.CurrentAgent()
return CurrentAgentInfo{
Name: currentAgent.Name(),
Description: currentAgent.Description(),
Commands: currentAgent.Commands(),
}
}
func (r *LocalRuntime) SetCurrentAgent(agentName string) error {
// Validate that the agent exists in the team
if _, err := r.team.Agent(agentName); err != nil {
return err
}
r.currentAgent = agentName
slog.Debug("Switched current agent", "agent", agentName)
return nil
}
func (r *LocalRuntime) CurrentAgentCommands(context.Context) types.Commands {
return r.CurrentAgent().Commands()
}
// CurrentAgentTools returns the tools available to the current agent.
// This starts the toolsets if needed and returns all available tools.
func (r *LocalRuntime) CurrentAgentTools(ctx context.Context) ([]tools.Tool, error) {
a := r.CurrentAgent()
return a.Tools(ctx)
}
// CurrentMCPPrompts returns the available MCP prompts from all active MCP toolsets
// for the current agent. It discovers prompts by calling ListPrompts on each MCP toolset
// and aggregates the results into a map keyed by prompt name.
func (r *LocalRuntime) CurrentMCPPrompts(ctx context.Context) map[string]mcptools.PromptInfo {
prompts := make(map[string]mcptools.PromptInfo)
// Get the current agent to access its toolsets
currentAgent := r.CurrentAgent()
if currentAgent == nil {
slog.Warn("No current agent available for MCP prompt discovery")
return prompts
}
// Iterate through all toolsets of the current agent
for _, toolset := range currentAgent.ToolSets() {
if mcpToolset, ok := tools.As[*mcptools.Toolset](toolset); ok {
slog.Debug("Found MCP toolset", "toolset", mcpToolset)
// Discover prompts from this MCP toolset
mcpPrompts := r.discoverMCPPrompts(ctx, mcpToolset)
// Merge prompts into the result map
// If there are name conflicts, the later toolset's prompt will override
maps.Copy(prompts, mcpPrompts)
} else {
slog.Debug("Toolset is not an MCP toolset", "type", fmt.Sprintf("%T", toolset))
}
}
slog.Debug("Discovered MCP prompts", "agent", currentAgent.Name(), "prompt_count", len(prompts))
return prompts
}
// discoverMCPPrompts queries an MCP toolset for available prompts and converts them
// to PromptInfo structures. This method handles the MCP protocol communication
// and gracefully handles any errors during prompt discovery.
func (r *LocalRuntime) discoverMCPPrompts(ctx context.Context, toolset *mcptools.Toolset) map[string]mcptools.PromptInfo {
mcpPrompts, err := toolset.ListPrompts(ctx)
if err != nil {
slog.Warn("Failed to list MCP prompts from toolset", "error", err)
return nil
}
prompts := make(map[string]mcptools.PromptInfo, len(mcpPrompts))
for _, mcpPrompt := range mcpPrompts {
promptInfo := mcptools.PromptInfo{
Name: mcpPrompt.Name,
Description: mcpPrompt.Description,
Arguments: make([]mcptools.PromptArgument, 0, len(mcpPrompt.Arguments)),
}
for _, arg := range mcpPrompt.Arguments {
promptInfo.Arguments = append(promptInfo.Arguments, mcptools.PromptArgument{
Name: arg.Name,
Description: arg.Description,
Required: arg.Required,
})
}
prompts[mcpPrompt.Name] = promptInfo
slog.Debug("Discovered MCP prompt", "name", mcpPrompt.Name, "args_count", len(promptInfo.Arguments))
}
return prompts
}
// CurrentAgent returns the current agent
func (r *LocalRuntime) CurrentAgent() *agent.Agent {
// We validated already that the agent exists
current, _ := r.team.Agent(r.currentAgent)
return current
}
// CurrentAgentSkillsEnabled returns whether skills are enabled for the current agent.
func (r *LocalRuntime) CurrentAgentSkillsEnabled() bool {
a := r.CurrentAgent()
return a != nil && a.SkillsEnabled()
}
// ExecuteMCPPrompt executes an MCP prompt with provided arguments and returns the content.
func (r *LocalRuntime) ExecuteMCPPrompt(ctx context.Context, promptName string, arguments map[string]string) (string, error) {
currentAgent := r.CurrentAgent()
if currentAgent == nil {
return "", fmt.Errorf("no current agent available")
}
for _, toolset := range currentAgent.ToolSets() {
mcpToolset, ok := tools.As[*mcptools.Toolset](toolset)
if !ok {
continue
}
result, err := mcpToolset.GetPrompt(ctx, promptName, arguments)
if err != nil {
// If error is "prompt not found", continue to next toolset
if err.Error() == "prompt not found" {
continue
}
return "", fmt.Errorf("error executing prompt '%s': %w", promptName, err)
}
// Convert the MCP result to a string format
if len(result.Messages) == 0 {
return "No content returned from MCP prompt", nil
}
var content strings.Builder
for i, message := range result.Messages {
if i > 0 {
content.WriteString("\n\n")
}
if textContent, ok := message.Content.(*mcp.TextContent); ok {
content.WriteString(textContent.Text)
} else {
content.WriteString(fmt.Sprintf("[Non-text content: %T]", message.Content))
}
}
return content.String(), nil
}
return "", fmt.Errorf("MCP prompt '%s' not found in any active toolset", promptName)
}
// TitleGenerator returns a title generator for automatic session title generation.
func (r *LocalRuntime) TitleGenerator() *sessiontitle.Generator {
a := r.CurrentAgent()
if a == nil {
return nil
}
model := a.Model()
if model == nil {
return nil
}
return sessiontitle.New(model, a.FallbackModels()...)
}
// getHooksExecutor creates a hooks executor for the given agent
func (r *LocalRuntime) getHooksExecutor(a *agent.Agent) *hooks.Executor {
hooksCfg := hooks.FromConfig(a.Hooks())
if hooksCfg == nil || hooksCfg.IsEmpty() {
return nil
}
return hooks.NewExecutor(hooksCfg, r.workingDir, r.env)
}
// getAgentModelID returns the model ID for an agent, or empty string if no model is set.
func getAgentModelID(a *agent.Agent) string {
if model := a.Model(); model != nil {
return model.ID()
}
return ""
}
// getEffectiveModelID returns the currently active model ID for an agent, accounting
// for any active fallback cooldown. During a cooldown period, this returns the fallback
// model ID instead of the configured primary model, so the UI reflects the actual model in use.
func (r *LocalRuntime) getEffectiveModelID(a *agent.Agent) string {
cooldownState := r.getCooldownState(a.Name())
if cooldownState != nil {
fallbacks := a.FallbackModels()
if cooldownState.fallbackIndex >= 0 && cooldownState.fallbackIndex < len(fallbacks) {
return fallbacks[cooldownState.fallbackIndex].ID()
}
}
return getAgentModelID(a)
}
// agentDetailsFromTeam converts team agent info to AgentDetails for events.
// It accounts for active fallback cooldowns, returning the effective model
// instead of the configured model when a fallback is in effect.
func (r *LocalRuntime) agentDetailsFromTeam() []AgentDetails {
agentsInfo := r.team.AgentsInfo()
details := make([]AgentDetails, len(agentsInfo))
for i, info := range agentsInfo {
providerName := info.Provider
modelName := info.Model
// Check if this agent has an active fallback cooldown
cooldownState := r.getCooldownState(info.Name)
if cooldownState != nil {
// Get the agent to access fallback models
if a, err := r.team.Agent(info.Name); err == nil && a != nil {
fallbacks := a.FallbackModels()
if cooldownState.fallbackIndex >= 0 && cooldownState.fallbackIndex < len(fallbacks) {
fb := fallbacks[cooldownState.fallbackIndex]
// Parse provider/model from the fallback model ID
modelID := fb.ID()
if p, m, found := strings.Cut(modelID, "/"); found {
providerName = p
modelName = m
} else {
modelName = modelID
}
}
}
}
details[i] = AgentDetails{
Name: info.Name,
Description: info.Description,
Provider: providerName,
Model: modelName,
Commands: info.Commands,
}
}
return details
}
// SessionStore returns the session store for browsing/loading past sessions.
func (r *LocalRuntime) SessionStore() session.Store {
return r.sessionStore
}
// UpdateSessionTitle persists the session title via the session store.
func (r *LocalRuntime) UpdateSessionTitle(ctx context.Context, sess *session.Session, title string) error {
sess.Title = title
if r.sessionStore != nil {
return r.sessionStore.UpdateSession(ctx, sess)
}
return nil
}
// PermissionsInfo returns the team-level permission patterns.
// Returns nil if no permissions are configured.
func (r *LocalRuntime) PermissionsInfo() *PermissionsInfo {
permChecker := r.team.Permissions()
if permChecker == nil || permChecker.IsEmpty() {
return nil
}
return &PermissionsInfo{
Allow: permChecker.AllowPatterns(),
Deny: permChecker.DenyPatterns(),
}
}
// ResetStartupInfo resets the startup info emission flag.
// This should be called when replacing a session to allow re-emission of
// agent, team, and toolset info to the UI.
func (r *LocalRuntime) ResetStartupInfo() {
r.startupInfoEmitted = false
}
// EmitStartupInfo emits initial agent, team, and toolset information for immediate sidebar display
func (r *LocalRuntime) EmitStartupInfo(ctx context.Context, events chan Event) {
// Prevent duplicate emissions
if r.startupInfoEmitted {
return
}
r.startupInfoEmitted = true
a := r.CurrentAgent()
// Helper to send events with context check
send := func(event Event) bool {
select {
case events <- event:
return true
case <-ctx.Done():
return false
}
}
// Emit agent and team information immediately for fast sidebar display
// Use getEffectiveModelID to account for active fallback cooldowns
if !send(AgentInfo(a.Name(), r.getEffectiveModelID(a), a.Description(), a.WelcomeMessage())) {
return
}
if !send(TeamInfo(r.agentDetailsFromTeam(), r.currentAgent)) {
return
}
// Emit agent warnings (if any) - these are quick
r.emitAgentWarningsWithSend(a, send)
// Tool loading can be slow (MCP servers need to start)
// Emit progressive updates as each toolset loads
r.emitToolsProgressively(ctx, a, send)
}
// emitToolsProgressively loads tools from each toolset and emits progress updates.
// This allows the UI to show the tool count incrementally as each toolset loads,
// with a spinner indicating that more tools may be coming.
func (r *LocalRuntime) emitToolsProgressively(ctx context.Context, a *agent.Agent, send func(Event) bool) {
toolsets := a.ToolSets()
totalToolsets := len(toolsets)
// If no toolsets, emit final state immediately
if totalToolsets == 0 {
send(ToolsetInfo(0, false, r.currentAgent))
return
}
// Emit initial loading state
if !send(ToolsetInfo(0, true, r.currentAgent)) {
return
}
// Load tools from each toolset and emit progress
var totalTools int
for i, toolset := range toolsets {
// Check context before potentially slow operations
if ctx.Err() != nil {
return
}
isLast := i == totalToolsets-1
// Start the toolset if needed
if startable, ok := toolset.(*tools.StartableToolSet); ok {
if !startable.IsStarted() {
if err := startable.Start(ctx); err != nil {
slog.Warn("Toolset start failed; skipping", "agent", a.Name(), "toolset", fmt.Sprintf("%T", startable.ToolSet), "error", err)
continue
}
}
}
// Get tools from this toolset
ts, err := toolset.Tools(ctx)
if err != nil {
slog.Warn("Failed to get tools from toolset", "agent", a.Name(), "error", err)
continue
}
totalTools += len(ts)
// Emit progress update - still loading unless this is the last toolset
if !send(ToolsetInfo(totalTools, !isLast, r.currentAgent)) {
return
}
}
// Emit final state (not loading)
send(ToolsetInfo(totalTools, false, r.currentAgent))
}
// registerDefaultTools registers the default tool handlers
func (r *LocalRuntime) registerDefaultTools() {
slog.Debug("Registering default tools")
tt := builtin.NewTransferTaskTool()
ht := builtin.NewHandoffTool()
ttTools, _ := tt.Tools(context.TODO())
htTools, _ := ht.Tools(context.TODO())
allTools := append(ttTools, htTools...)
handlers := map[string]ToolHandlerFunc{
builtin.ToolNameTransferTask: r.handleTaskTransfer,
builtin.ToolNameHandoff: r.handleHandoff,
}
for _, t := range allTools {
if h, exists := handlers[t.Name]; exists {
r.toolMap[t.Name] = ToolHandler{handler: h, tool: t}
} else {
slog.Warn("No handler found for default tool", "tool", t.Name)
}
}
slog.Debug("Registered default tools", "count", len(r.toolMap))
}
func (r *LocalRuntime) finalizeEventChannel(ctx context.Context, sess *session.Session, events chan Event) {
defer close(events)
events <- StreamStopped(sess.ID, r.currentAgent)
telemetry.RecordSessionEnd(ctx)
}
// RunStream starts the agent's interaction loop and returns a channel of events
func (r *LocalRuntime) RunStream(ctx context.Context, sess *session.Session) <-chan Event {
slog.Debug("Starting runtime stream", "agent", r.currentAgent, "session_id", sess.ID)
events := make(chan Event, 128)
go func() {
telemetry.RecordSessionStart(ctx, r.currentAgent, sess.ID)
ctx, sessionSpan := r.startSpan(ctx, "runtime.session", trace.WithAttributes(
attribute.String("agent", r.currentAgent),
attribute.String("session.id", sess.ID),
))
defer sessionSpan.End()
// Set the events channel for elicitation requests
r.setElicitationEventsChannel(events)
defer r.clearElicitationEventsChannel()
// Set elicitation handler on all MCP toolsets before getting tools
a := r.CurrentAgent()
// Emit agent information for sidebar display
// Use getEffectiveModelID to account for active fallback cooldowns
events <- AgentInfo(a.Name(), r.getEffectiveModelID(a), a.Description(), a.WelcomeMessage())
// Emit team information
events <- TeamInfo(r.agentDetailsFromTeam(), r.currentAgent)
// Initialize RAG and forward events
r.InitializeRAG(ctx, events)
r.emitAgentWarnings(a, events)
r.configureToolsetHandlers(a, events)
agentTools, err := r.getTools(ctx, a, sessionSpan, events)
if err != nil {
events <- Error(fmt.Sprintf("failed to get tools: %v", err))
return
}
events <- ToolsetInfo(len(agentTools), false, r.currentAgent)
messages := sess.GetMessages(a)
if sess.SendUserMessage {
events <- UserMessage(messages[len(messages)-1].Content, sess.ID, len(sess.Messages)-1)
}
events <- StreamStarted(sess.ID, a.Name())
defer r.finalizeEventChannel(ctx, sess, events)
r.registerDefaultTools()
iteration := 0
// Use a runtime copy of maxIterations so we don't modify the session's persistent config
runtimeMaxIterations := sess.MaxIterations
for {
// Set elicitation handler on all MCP toolsets before getting tools
a := r.CurrentAgent()
r.emitAgentWarnings(a, events)
r.configureToolsetHandlers(a, events)
agentTools, err := r.getTools(ctx, a, sessionSpan, events)
if err != nil {
events <- Error(fmt.Sprintf("failed to get tools: %v", err))
return
}
// Check iteration limit
if runtimeMaxIterations > 0 && iteration >= runtimeMaxIterations {
slog.Debug(
"Maximum iterations reached",
"agent", a.Name(),
"iterations", iteration,
"max", runtimeMaxIterations,
)
events <- MaxIterationsReached(runtimeMaxIterations)
// Wait for user decision (resume / reject)
select {
case req := <-r.resumeChan:
if req.Type == ResumeTypeApprove {
slog.Debug("User chose to continue after max iterations", "agent", a.Name())
runtimeMaxIterations = iteration + 10
} else {
slog.Debug("User rejected continuation", "agent", a.Name())
assistantMessage := chat.Message{
Role: chat.MessageRoleAssistant,
Content: fmt.Sprintf(
"Execution stopped after reaching the configured max_iterations limit (%d).",
runtimeMaxIterations,
),
CreatedAt: time.Now().Format(time.RFC3339),
}
addAgentMessage(sess, a, &assistantMessage, events)
return
}
case <-ctx.Done():
slog.Debug(
"Context cancelled while waiting for resume confirmation",
"agent", a.Name(),
"session_id", sess.ID,
)
return
}
}
iteration++
// Exit immediately if the stream context has been cancelled (e.g., Ctrl+C)
if err := ctx.Err(); err != nil {
slog.Debug("Runtime stream context cancelled, stopping loop", "agent", a.Name(), "session_id", sess.ID)
return
}
slog.Debug("Starting conversation loop iteration", "agent", a.Name())
streamCtx, streamSpan := r.startSpan(ctx, "runtime.stream", trace.WithAttributes(
attribute.String("agent", a.Name()),
attribute.String("session.id", sess.ID),
))
model := a.Model()
// Apply thinking setting based on session state.
// When thinking is disabled: clone with thinking=false to clear any thinking config.
// When thinking is enabled: clone with thinking=true to ensure defaults are applied
// (this handles models with no thinking config, explicitly disabled thinking, or
// models that already have thinking configured).
if !sess.Thinking {
model = provider.CloneWithOptions(ctx, model, options.WithThinking(false))
slog.Debug("Cloned provider with thinking disabled", "agent", a.Name(), "model", model.ID())
} else {
// Always clone with thinking=true when session has thinking enabled.
// applyOverrides will apply provider defaults if ThinkingBudget is nil or disabled.
model = provider.CloneWithOptions(ctx, model, options.WithThinking(true))
slog.Debug("Cloned provider with thinking enabled", "agent", a.Name(), "model", model.ID())
}
modelID := model.ID()
slog.Debug("Using agent", "agent", a.Name(), "model", modelID)
slog.Debug("Getting model definition", "model_id", modelID)
m, err := r.modelsStore.GetModel(ctx, modelID)
if err != nil {
slog.Debug("Failed to get model definition", "error", err)
}
var contextLimit int64
if m != nil {
contextLimit = int64(m.Limit.Context)
}
if m != nil && r.sessionCompaction {
if sess.InputTokens+sess.OutputTokens > int64(float64(contextLimit)*0.9) {
r.Summarize(ctx, sess, "", events)
events <- TokenUsage(sess.ID, r.currentAgent, sess.InputTokens, sess.OutputTokens, sess.InputTokens+sess.OutputTokens, contextLimit, sess.Cost)
}
}
messages := sess.GetMessages(a)
slog.Debug("Retrieved messages for processing", "agent", a.Name(), "message_count", len(messages))
// Try primary model with fallback chain if configured
res, usedModel, err := r.tryModelWithFallback(streamCtx, a, model, messages, agentTools, sess, m, events)
if err != nil {