-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmanager.go
More file actions
618 lines (521 loc) · 16.3 KB
/
Copy pathmanager.go
File metadata and controls
618 lines (521 loc) · 16.3 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
package agent
import (
"context"
"fmt"
"sync"
"github.com/google/uuid"
agentruntime "github.com/philjestin/boatman-ecosystem/shared/agentruntime"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// AuthConfig holds authentication configuration
type AuthConfig struct {
Method string // "anthropic-api" or "google-cloud"
APIKey string
GCPProjectID string
GCPRegion string
ApprovalMode string // "suggest", "auto-edit", "full-auto"
}
// ConfigGetter retrieves memory management configuration
type ConfigGetter interface {
GetMaxMessagesPerSession() int
GetArchiveOldMessages() bool
GetMaxSessionAgeDays() int
GetMaxTotalSessions() int
GetAutoCleanupSessions() bool
GetMaxAgentsPerSession() int
GetKeepCompletedAgents() bool
GetMCPServerNames() []string
}
// Manager handles multiple agent sessions
type Manager struct {
ctx context.Context
wailsReady bool // true after SetContext is called with a valid Wails context
sessions map[string]*Session
mu sync.RWMutex
defaultModel string
authConfigGetter func() AuthConfig
configGetter ConfigGetter
}
// RoutineSessionOptions describes a routine-backed chat session. Routine
// executions use ordinary sessions so users can continue the same runtime agent.
type RoutineSessionOptions struct {
RoutineID string
RoutineName string
Profile string
Provider string
Model string
ReasoningEffort string
Instructions string
Values map[string]string
MCPServers []agentruntime.MCPServerRef
}
// NewManager creates a new agent manager
func NewManager() *Manager {
return &Manager{
sessions: make(map[string]*Session),
defaultModel: "sonnet",
}
}
// SetContext sets the Wails runtime context and enables event emission.
// This should be called from the Wails OnStartup lifecycle hook with the
// context provided by Wails. Calling with context.Background() or other
// non-Wails contexts will store the context but not enable event emission.
func (m *Manager) SetContext(ctx context.Context) {
m.ctx = ctx
}
// SetWailsReady marks the manager as ready to emit Wails events.
// Call this after SetContext with a valid Wails context.
func (m *Manager) SetWailsReady() {
m.wailsReady = true
}
// SetDefaultModel sets the default model for new sessions
func (m *Manager) SetDefaultModel(model string) {
m.mu.Lock()
defer m.mu.Unlock()
m.defaultModel = model
}
// SetAuthConfigGetter sets the function to retrieve auth configuration
func (m *Manager) SetAuthConfigGetter(getter func() AuthConfig) {
m.mu.Lock()
defer m.mu.Unlock()
m.authConfigGetter = getter
}
// SetAPIKeyGetter sets the function to retrieve the API key (deprecated, use SetAuthConfigGetter)
func (m *Manager) SetAPIKeyGetter(getter func() string) {
m.mu.Lock()
defer m.mu.Unlock()
m.authConfigGetter = func() AuthConfig {
return AuthConfig{
Method: "anthropic-api",
APIKey: getter(),
}
}
}
// SetConfigGetter sets the config getter for memory management settings
func (m *Manager) SetConfigGetter(getter ConfigGetter) {
m.mu.Lock()
defer m.mu.Unlock()
m.configGetter = getter
}
// GetConfigGetter returns the config getter
func (m *Manager) GetConfigGetter() ConfigGetter {
m.mu.RLock()
defer m.mu.RUnlock()
return m.configGetter
}
// CreateSession creates a new agent session for a project
func (m *Manager) CreateSession(projectPath string) (*Session, error) {
m.mu.Lock()
defer m.mu.Unlock()
sessionID := uuid.New().String()
session := NewSession(sessionID, projectPath)
// Set up event handlers
m.setupSessionHandlers(session, sessionID)
// Set trim settings from config
if m.configGetter != nil {
maxMessages := m.configGetter.GetMaxMessagesPerSession()
archive := m.configGetter.GetArchiveOldMessages()
session.SetTrimSettings(maxMessages, archive)
// Set agent cleanup settings
maxAgents := m.configGetter.GetMaxAgentsPerSession()
keepCompleted := m.configGetter.GetKeepCompletedAgents()
session.SetAgentCleanupSettings(maxAgents, keepCompleted)
}
m.sessions[sessionID] = session
return session, nil
}
// CreateFirefighterSession creates a new firefighter agent session
func (m *Manager) CreateFirefighterSession(projectPath string, scope string, slackChannels string) (*Session, error) {
m.mu.Lock()
defer m.mu.Unlock()
sessionID := uuid.New().String()
session := NewSession(sessionID, projectPath)
session.Mode = "firefighter"
session.ModeConfig = map[string]interface{}{
"scope": scope,
"slackChannels": slackChannels,
}
// Store available MCP server names so the prompt only references tools that exist
if m.configGetter != nil {
session.ModeConfig["mcpServers"] = m.configGetter.GetMCPServerNames()
}
session.Tags = append(session.Tags, "firefighter")
// Set up event handlers
m.setupSessionHandlers(session, sessionID)
// Set trim settings from config
if m.configGetter != nil {
maxMessages := m.configGetter.GetMaxMessagesPerSession()
archive := m.configGetter.GetArchiveOldMessages()
session.SetTrimSettings(maxMessages, archive)
// Set agent cleanup settings
maxAgents := m.configGetter.GetMaxAgentsPerSession()
keepCompleted := m.configGetter.GetKeepCompletedAgents()
session.SetAgentCleanupSettings(maxAgents, keepCompleted)
}
m.sessions[sessionID] = session
return session, nil
}
// CreateBoatmanModeSession creates a new boatmanmode agent session
// mode can be "ticket" or "prompt"
func (m *Manager) CreateBoatmanModeSession(projectPath string, input string, mode string) (*Session, error) {
m.mu.Lock()
defer m.mu.Unlock()
sessionID := uuid.New().String()
session := NewSession(sessionID, projectPath)
session.Mode = "boatmanmode"
session.ModeConfig = map[string]interface{}{
"input": input,
"mode": mode,
}
session.Tags = append(session.Tags, "boatmanmode")
// Set up event handlers
m.setupSessionHandlers(session, sessionID)
// Set trim settings from config — boatmanmode sessions produce significantly
// more messages than interactive sessions, so use a higher limit.
if m.configGetter != nil {
maxMessages := m.configGetter.GetMaxMessagesPerSession()
if maxMessages < 5000 {
maxMessages = 5000
}
archive := m.configGetter.GetArchiveOldMessages()
session.SetTrimSettings(maxMessages, archive)
// Set agent cleanup settings
maxAgents := m.configGetter.GetMaxAgentsPerSession()
keepCompleted := m.configGetter.GetKeepCompletedAgents()
session.SetAgentCleanupSettings(maxAgents, keepCompleted)
}
m.sessions[sessionID] = session
return session, nil
}
// CreateTriageSession creates a new triage agent session.
func (m *Manager) CreateTriageSession(projectPath string) (*Session, error) {
m.mu.Lock()
defer m.mu.Unlock()
sessionID := uuid.New().String()
session := NewSession(sessionID, projectPath)
session.Mode = "triage"
session.ModeConfig = map[string]interface{}{}
session.Tags = append(session.Tags, "triage")
m.setupSessionHandlers(session, sessionID)
if m.configGetter != nil {
maxMessages := m.configGetter.GetMaxMessagesPerSession()
archive := m.configGetter.GetArchiveOldMessages()
session.SetTrimSettings(maxMessages, archive)
maxAgents := m.configGetter.GetMaxAgentsPerSession()
keepCompleted := m.configGetter.GetKeepCompletedAgents()
session.SetAgentCleanupSettings(maxAgents, keepCompleted)
}
m.sessions[sessionID] = session
return session, nil
}
// CreateRoutineSession creates a new session tied to a routine execution.
func (m *Manager) CreateRoutineSession(projectPath string, sessionID string, opts RoutineSessionOptions) (*Session, error) {
m.mu.Lock()
defer m.mu.Unlock()
if sessionID == "" {
sessionID = uuid.New().String()
}
if _, exists := m.sessions[sessionID]; exists {
return nil, fmt.Errorf("session already exists: %s", sessionID)
}
model := opts.Model
if model == "" {
model = m.defaultModel
}
effort := opts.ReasoningEffort
if effort == "" {
effort = "medium"
}
profile := opts.Profile
if profile == "" {
profile = "desktop-routine"
}
session := NewSession(sessionID, projectPath)
session.Model = model
session.ReasoningEffort = effort
session.Mode = "routine"
session.ModeConfig = map[string]interface{}{
"routineId": opts.RoutineID,
"routineName": opts.RoutineName,
"profile": profile,
"provider": opts.Provider,
"mcpServers": opts.MCPServers,
"values": cloneStringMap(opts.Values),
}
session.systemPrompt = opts.Instructions
session.Tags = append(session.Tags, "routine", opts.RoutineID)
m.setupSessionHandlers(session, sessionID)
if m.configGetter != nil {
maxMessages := m.configGetter.GetMaxMessagesPerSession()
if maxMessages < 1000 {
maxMessages = 1000
}
archive := m.configGetter.GetArchiveOldMessages()
session.SetTrimSettings(maxMessages, archive)
maxAgents := m.configGetter.GetMaxAgentsPerSession()
keepCompleted := m.configGetter.GetKeepCompletedAgents()
session.SetAgentCleanupSettings(maxAgents, keepCompleted)
}
m.sessions[sessionID] = session
return session, nil
}
func cloneStringMap(values map[string]string) map[string]string {
if len(values) == 0 {
return nil
}
out := make(map[string]string, len(values))
for key, value := range values {
out[key] = value
}
return out
}
// setupSessionHandlers sets up event handlers for a session
func (m *Manager) setupSessionHandlers(session *Session, sessionID string) {
session.SetMessageHandler(func(msg Message) {
if m.wailsReady {
runtime.EventsEmit(m.ctx, "agent:message", map[string]interface{}{
"sessionId": sessionID,
"message": msg,
})
}
})
session.SetTaskHandler(func(task Task) {
if m.wailsReady {
runtime.EventsEmit(m.ctx, "agent:task", map[string]interface{}{
"sessionId": sessionID,
"task": task,
})
}
})
session.SetStatusHandler(func(status SessionStatus) {
if m.wailsReady {
runtime.EventsEmit(m.ctx, "agent:status", map[string]interface{}{
"sessionId": sessionID,
"status": status,
})
}
})
}
// GetSession returns a session by ID
func (m *Manager) GetSession(sessionID string) (*Session, error) {
m.mu.RLock()
defer m.mu.RUnlock()
session, ok := m.sessions[sessionID]
if !ok {
return nil, fmt.Errorf("session not found: %s", sessionID)
}
return session, nil
}
// ListSessions returns all active sessions
func (m *Manager) ListSessions() []*Session {
m.mu.RLock()
defer m.mu.RUnlock()
sessions := make([]*Session, 0, len(m.sessions))
for _, s := range m.sessions {
sessions = append(sessions, s)
}
return sessions
}
// StartSession starts an agent session
func (m *Manager) StartSession(sessionID string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
m.mu.RLock()
model := m.defaultModel
configGetter := m.configGetter
m.mu.RUnlock()
// Update trim settings in case they changed
if configGetter != nil {
maxMessages := configGetter.GetMaxMessagesPerSession()
archive := configGetter.GetArchiveOldMessages()
session.SetTrimSettings(maxMessages, archive)
// Update agent cleanup settings
maxAgents := configGetter.GetMaxAgentsPerSession()
keepCompleted := configGetter.GetKeepCompletedAgents()
session.SetAgentCleanupSettings(maxAgents, keepCompleted)
}
return session.Start(model)
}
// StopSession stops an agent session
func (m *Manager) StopSession(sessionID string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
return session.Stop()
}
// DeleteSession removes a session
func (m *Manager) DeleteSession(sessionID string) error {
m.mu.Lock()
defer m.mu.Unlock()
session, ok := m.sessions[sessionID]
if !ok {
return fmt.Errorf("session not found: %s", sessionID)
}
session.Stop()
delete(m.sessions, sessionID)
// Remove persisted file from disk
if err := DeleteSessionFile(sessionID); err != nil {
fmt.Printf("Warning: failed to delete session file %s: %v\n", sessionID, err)
}
return nil
}
// SendMessage sends a message to a session
func (m *Manager) SendMessage(sessionID, content string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
// Get auth config
var authConfig AuthConfig
m.mu.RLock()
if m.authConfigGetter != nil {
authConfig = m.authConfigGetter()
}
m.mu.RUnlock()
return session.SendMessage(content, authConfig)
}
// ApproveAction approves a pending action
func (m *Manager) ApproveAction(sessionID, actionID string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
return session.Approve(actionID)
}
// RejectAction rejects a pending action
func (m *Manager) RejectAction(sessionID, actionID string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
return session.Reject(actionID)
}
// GetSessionMessages returns messages for a session
func (m *Manager) GetSessionMessages(sessionID string) ([]Message, error) {
session, err := m.GetSession(sessionID)
if err != nil {
return nil, err
}
return session.GetMessages(), nil
}
// GetSessionTasks returns tasks for a session
func (m *Manager) GetSessionTasks(sessionID string) ([]Task, error) {
session, err := m.GetSession(sessionID)
if err != nil {
return nil, err
}
return session.GetTasks(), nil
}
// StopAllSessions stops all running sessions
func (m *Manager) StopAllSessions() {
m.mu.Lock()
defer m.mu.Unlock()
for _, session := range m.sessions {
session.Stop()
}
}
// LoadPersistedSessions loads all sessions from disk and registers them in the manager.
// Should be called once during startup, after SetContext/SetWailsReady/SetConfigGetter.
func (m *Manager) LoadPersistedSessions() error {
sessions, err := LoadAllSessions()
if err != nil {
return fmt.Errorf("failed to load persisted sessions: %w", err)
}
m.mu.Lock()
defer m.mu.Unlock()
for _, session := range sessions {
// Wire up Wails event handlers
m.setupSessionHandlers(session, session.ID)
// Apply config settings
if m.configGetter != nil {
maxMessages := m.configGetter.GetMaxMessagesPerSession()
archive := m.configGetter.GetArchiveOldMessages()
session.SetTrimSettings(maxMessages, archive)
maxAgents := m.configGetter.GetMaxAgentsPerSession()
keepCompleted := m.configGetter.GetKeepCompletedAgents()
session.SetAgentCleanupSettings(maxAgents, keepCompleted)
}
m.sessions[session.ID] = session
}
return nil
}
// SaveAllSessions persists all sessions to disk.
// Used on shutdown to preserve session state.
func (m *Manager) SaveAllSessions() {
m.mu.RLock()
defer m.mu.RUnlock()
for _, session := range m.sessions {
if err := SaveSession(session); err != nil {
fmt.Printf("Warning: failed to save session %s: %v\n", session.ID, err)
}
}
}
// CleanupSessions removes old sessions based on config settings
func (m *Manager) CleanupSessions() (int, error) {
m.mu.RLock()
configGetter := m.configGetter
m.mu.RUnlock()
if configGetter == nil || !configGetter.GetAutoCleanupSessions() {
return 0, nil
}
maxAgeDays := configGetter.GetMaxSessionAgeDays()
maxTotal := configGetter.GetMaxTotalSessions()
return CleanupOldSessions(maxAgeDays, maxTotal)
}
// MarkAgentCompleted marks an agent as completed
func (m *Manager) MarkAgentCompleted(sessionID, agentID string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
session.MarkAgentCompleted(agentID)
return nil
}
// AddTag adds a tag to a session
func (m *Manager) AddTag(sessionID, tag string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
session.AddTag(tag)
return SaveSession(session)
}
// RemoveTag removes a tag from a session
func (m *Manager) RemoveTag(sessionID, tag string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
session.RemoveTag(tag)
return SaveSession(session)
}
// SetSessionModel updates the model for a session
func (m *Manager) SetSessionModel(sessionID, model string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
session.SetModel(model)
return SaveSession(session)
}
// SetSessionReasoningEffort updates the reasoning effort for a session
func (m *Manager) SetSessionReasoningEffort(sessionID, effort string) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
session.SetReasoningEffort(effort)
return SaveSession(session)
}
// SetFavorite sets the favorite status of a session
func (m *Manager) SetFavorite(sessionID string, favorite bool) error {
session, err := m.GetSession(sessionID)
if err != nil {
return err
}
session.SetFavorite(favorite)
return SaveSession(session)
}