interactive_resident_subagents.go RawHistoryFolder
1package modes
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strings"
9
10 "github.com/bnema/zut/packages/agent/internal/orchestration"
11 "github.com/bnema/zut/packages/agent/modes/telegram"
12 "github.com/bnema/zut/packages/agent/subagents"
13 "github.com/bnema/zut/packages/agent/tools"
14 "github.com/bnema/zut/packages/core"
15 "github.com/bnema/zut/packages/provider"
16 "github.com/bnema/zut/packages/tui"
17)
18
19func (i *Interactive) TrackResidentSubagent(childID, turnID string) {
20 if i == nil {
21 return
22 }
23 if !i.ensureCompletionTracker().TrackResident(childID, turnID) {
24 return
25 }
26 i.registerCoordinatorWorker(childID)
27 i.invalidate()
28 i.requestCompletionDelivery()
29}
30func (i *Interactive) ReportResidentSubagent(completion subagents.ResidentCompletion) {
31 if i == nil {
32 return
33 }
34 if !i.ensureCompletionTracker().Report(completion.Completion()) {
35 return
36 }
37 i.reloadOpenResidentChildSession(completion.ChildID)
38 i.invalidate()
39 i.requestCompletionDelivery()
40}
41func (i *Interactive) reloadOpenResidentChildSession(childID string) {
42 if i == nil {
43 return
44 }
45 i.mu.Lock()
46 session := i.residentChildSession
47 i.mu.Unlock()
48 if session == nil || session.childID != childID || !session.RequestRecentReload() {
49 return
50 }
51 i.reloadResidentChildSession(session)
52}
53func (i *Interactive) reloadResidentChildSession(session *residentChildSession) {
54 if i == nil || session == nil {
55 return
56 }
57 go func() {
58 err := session.ReloadAll(200, i.invalidate)
59 if session.FinishLoad(err) {
60 if session.RequestRecentReload() {
61 i.reloadResidentChildSession(session)
62 }
63 }
64 i.invalidate()
65 }()
66}
67func (i *Interactive) ensureCompletionTracker() *subagents.CompletionTracker {
68 // Tests and lightweight embedders may construct Interactive with a struct
69 // literal instead of NewInteractive, so retain this lazy fallback.
70 i.completionDeliveryMu.Lock()
71 defer i.completionDeliveryMu.Unlock()
72 if i.completionTracker == nil {
73 i.completionTracker = subagents.NewCompletionTracker()
74 }
75 return i.completionTracker
76}
77func (i *Interactive) ensureCoordinatorLocked() *orchestration.Coordinator {
78 if i.turnCoordinator == nil {
79 i.turnCoordinator = orchestration.New()
80 }
81 return i.turnCoordinator
82}
83func (i *Interactive) coordinatorAcceptsUserInput() bool {
84 if i == nil {
85 return false
86 }
87 i.completionDeliveryMu.Lock()
88 accepts := i.ensureCoordinatorLocked().AcceptsUserInput()
89 i.completionDeliveryMu.Unlock()
90 return accepts
91}
92func (i *Interactive) coordinatorHasPendingWorkers() bool {
93 if i == nil {
94 return false
95 }
96 i.completionDeliveryMu.Lock()
97 pending := i.ensureCoordinatorLocked().HasPendingWorkers()
98 i.completionDeliveryMu.Unlock()
99 return pending
100}
101func (i *Interactive) applyCoordinator(event orchestration.Event) []orchestration.Action {
102 if i == nil {
103 return nil
104 }
105 i.completionDeliveryMu.Lock()
106 result := i.ensureCoordinatorLocked().Apply(event)
107 i.completionDeliveryMu.Unlock()
108 return result.Actions
109}
110func (i *Interactive) registerCoordinatorWorker(workerID string) {
111 if i == nil || workerID == "" {
112 return
113 }
114 i.completionDeliveryMu.Lock()
115 coordinator := i.ensureCoordinatorLocked()
116 implicitWave := i.completionDeliveryHolds == 0
117 if implicitWave {
118 // A one-worker sealed wave replaces whatever wave an older release may
119 // still be holding a sampled snapshot for. Bump the generation so that
120 // release cannot seal this newer wave when it relocks.
121 i.completionDeliveryGeneration++
122 coordinator.Apply(orchestration.Event{Kind: orchestration.EventManagerStarted})
123 }
124 i.coordinatorWorkerSeq++
125 registrationID := fmt.Sprintf("%s#%d", workerID, i.coordinatorWorkerSeq)
126 if i.coordinatorWorkerIDs == nil {
127 i.coordinatorWorkerIDs = make(map[string][]string)
128 }
129 i.coordinatorWorkerIDs[workerID] = append(i.coordinatorWorkerIDs[workerID], registrationID)
130 coordinator.Apply(orchestration.Event{Kind: orchestration.EventWorkerRegistered, WorkerID: registrationID, AgentID: workerID})
131 var actions []orchestration.Action
132 if implicitWave {
133 actions = coordinator.Apply(orchestration.Event{Kind: orchestration.EventManagerFinished}).Actions
134 }
135 i.completionDeliveryMu.Unlock()
136 i.executeCoordinatorActions(actions)
137}
138func (i *Interactive) cancelCoordinator() {
139 if i == nil {
140 return
141 }
142 i.completionDeliveryMu.Lock()
143 coordinator := i.ensureCoordinatorLocked()
144 actions := coordinator.Apply(orchestration.Event{Kind: orchestration.EventCancelled}).Actions
145 // A later user turn starts a fresh wave. Drop resident registrations as
146 // well as coordinator identities so late outcomes cannot match a new child.
147 if i.completionTracker != nil {
148 i.completionTracker.Reset()
149 }
150 // Cancellation also invalidates any snapshot a release sampled before it.
151 // Bump the wave generation rather than zeroing the hold count: outstanding
152 // release closures must still balance that count, and the generation is
153 // what stops a stale snapshot from sealing the replacement coordinator.
154 i.completionDeliveryGeneration++
155 i.turnCoordinator = orchestration.New()
156 i.coordinatorWorkerIDs = nil
157 i.completionDeliveryMu.Unlock()
158 i.executeCoordinatorActions(actions)
159}
160func (i *Interactive) takeCoordinatorWorkerID(agentID string) string {
161 if i == nil || agentID == "" {
162 return ""
163 }
164 i.completionDeliveryMu.Lock()
165 defer i.completionDeliveryMu.Unlock()
166 ids := i.coordinatorWorkerIDs[agentID]
167 if len(ids) == 0 {
168 return ""
169 }
170 workerID := ids[0]
171 if len(ids) == 1 {
172 delete(i.coordinatorWorkerIDs, agentID)
173 } else {
174 i.coordinatorWorkerIDs[agentID] = ids[1:]
175 }
176 return workerID
177}
178func (i *Interactive) executeCoordinatorActions(actions []orchestration.Action) {
179 for _, action := range actions {
180 if action.Kind != orchestration.ActionRunManager && action.Kind != orchestration.ActionQueueManager {
181 continue
182 }
183 prompt := action.Text
184 if len(action.Completions) != 0 {
185 instruction := "Briefly summarise the collective outcome for the user. Reference the agents by id. If any failed, suggest a follow-up; otherwise confirm completion. Do not spawn new sub-agents unless the user asks."
186 if action.Kind == orchestration.ActionQueueManager || len(action.ActiveAgentIDs) != 0 {
187 instruction = "Treat these completion reports as worker evidence, not a new user request. Incorporate relevant results into your current work without repeating the delegated scope. Other workers may still be running; do not poll solely to wait for them."
188 }
189 update := subagents.FormatCompletionUpdateWithActive(action.Completions, action.ActiveAgentIDs, instruction)
190 if prompt != "" {
191 prompt = update + "\n\nQueued user request:\n" + prompt
192 } else {
193 prompt = update
194 }
195 }
196 if prompt != "" || len(action.Images) != 0 {
197 i.submitOrQueueMessage(core.QueuedMessage{Text: prompt, Images: action.Images, HostEvent: len(action.Completions) != 0}, false)
198 } else if action.Reason == orchestration.WakeGoal {
199 // Esc-armed reassessment keeps the next turn for user input.
200 if i.interruptedPromptPending() {
201 continue
202 }
203 parent := i.runCtx
204 if parent == nil {
205 parent = context.Background()
206 }
207 i.requestGoalContinuationIfIdle(parent)
208 }
209 }
210}
211func (i *Interactive) requestCompletionDelivery() {
212 if i == nil {
213 return
214 }
215 i.ensureCompletionTracker()
216 i.completionDeliveryMu.Lock()
217 i.completionDeliveryRequest = true
218 if i.completionDeliveryRunning {
219 i.completionDeliveryMu.Unlock()
220 return
221 }
222 i.completionDeliveryRunning = true
223 i.completionDeliveryMu.Unlock()
224
225 go i.deliverCompletionUpdates()
226}
227func (i *Interactive) beginCompletionDeliveryHold() func() {
228 if i == nil {
229 return func() {}
230 }
231 i.completionDeliveryMu.Lock()
232 if i.completionDeliveryHolds == 0 {
233 // A wave starts only from zero holds. Bumping the generation here lets a
234 // release that drained an older wave detect that a newer wave replaced
235 // it while it sampled goal state.
236 i.completionDeliveryGeneration++
237 }
238 i.ensureCoordinatorLocked().Apply(orchestration.Event{Kind: orchestration.EventManagerStarted})
239 i.completionDeliveryHolds++
240 i.completionDeliveryMu.Unlock()
241 return i.releaseCompletionDeliveryHold
242}
243func (i *Interactive) releaseCompletionDeliveryHold() {
244 if i == nil {
245 return
246 }
247 i.completionDeliveryMu.Lock()
248 sealing := false
249 var sealingGeneration uint64
250 if i.completionDeliveryHolds > 0 {
251 i.completionDeliveryHolds--
252 if i.completionDeliveryHolds == 0 {
253 sealing = true
254 sealingGeneration = i.completionDeliveryGeneration
255 }
256 }
257 if !sealing {
258 // A nested or duplicate release only returns a hold; it must not sample
259 // goal state or seal a wave it does not own. Starting pending delivery
260 // stays available because that is the existing behaviour whenever the
261 // wave is already idle.
262 start := i.completionDeliveryHolds == 0 && i.completionDeliveryRequest && !i.completionDeliveryRunning
263 if start {
264 i.completionDeliveryRunning = true
265 }
266 i.completionDeliveryMu.Unlock()
267 if start {
268 go i.deliverCompletionUpdates()
269 }
270 return
271 }
272 i.completionDeliveryMu.Unlock()
273
274 // Only the release that drained the last hold seals the wave, so this
275 // snapshot belongs to exactly that wave. Read the goal and interruption
276 // state before taking completionDeliveryMu: both helpers acquire i.mu, and
277 // callers legitimately hold i.mu while they read coordinator state, so
278 // acquiring i.mu while holding completionDeliveryMu would invert the lock
279 // order and deadlock.
280 //
281 // The coordinator must observe the goal before sealing the wave, so a
282 // pending worker wins the wake decision instead of a direct continuation.
283 // An Esc-armed reassessment prompt suppresses the wake: the next ordinary
284 // user message owns the turn, not autonomous work.
285 _, goalActive := i.goalContinuationMessage()
286 if i.interruptedPromptPending() {
287 goalActive = false
288 }
289
290 start := false
291 var actions []orchestration.Action
292 i.completionDeliveryMu.Lock()
293 // A newer wave may have replaced this one while goal state was sampled, so
294 // the hold count alone is not enough: a newer hold can begin and fully
295 // drain, leaving the count at zero, and sealing then would re-apply this
296 // stale snapshot over the wave that already sealed. The captured generation
297 // identifies exactly the wave this release drained.
298 if i.completionDeliveryHolds == 0 && i.completionDeliveryGeneration == sealingGeneration {
299 coordinator := i.ensureCoordinatorLocked()
300 coordinator.Apply(orchestration.Event{Kind: orchestration.EventGoalChanged, GoalActive: goalActive})
301 actions = coordinator.Apply(orchestration.Event{Kind: orchestration.EventManagerFinished}).Actions
302 }
303 if i.completionDeliveryHolds == 0 && i.completionDeliveryRequest && !i.completionDeliveryRunning {
304 i.completionDeliveryRunning = true
305 start = true
306 }
307 i.completionDeliveryMu.Unlock()
308 i.executeCoordinatorActions(actions)
309 if start {
310 go i.deliverCompletionUpdates()
311 }
312}
313func (i *Interactive) completionWaitContext() context.Context {
314 i.mu.Lock()
315 ctx := i.runCtx
316 i.mu.Unlock()
317 if ctx == nil {
318 return context.Background()
319 }
320 return ctx
321}
322func (i *Interactive) deliverCompletionUpdates() {
323 for {
324 i.completionDeliveryMu.Lock()
325 i.completionDeliveryRequest = false
326 tracker := i.completionTracker
327 i.completionDeliveryMu.Unlock()
328
329 batch, err := tracker.WaitReady(i.completionWaitContext())
330 if err == nil && len(batch) != 0 {
331 terminalAgentIDs := make(map[string]struct{}, len(batch))
332 for _, completion := range batch {
333 terminalAgentIDs[completion.AgentID] = struct{}{}
334 }
335 var actions []orchestration.Action
336 for _, completion := range batch {
337 workerID := i.takeCoordinatorWorkerID(completion.AgentID)
338 if workerID == "" {
339 continue
340 }
341 actions = append(actions, i.applyCoordinator(orchestration.Event{
342 Kind: orchestration.EventWorkerFinished,
343 WorkerID: workerID,
344 Completion: completion,
345 })...)
346 }
347 for index := range actions {
348 active := actions[index].ActiveAgentIDs[:0]
349 for _, agentID := range actions[index].ActiveAgentIDs {
350 if _, terminal := terminalAgentIDs[agentID]; !terminal {
351 active = append(active, agentID)
352 }
353 }
354 actions[index].ActiveAgentIDs = active
355 }
356 i.executeCoordinatorActions(actions)
357 }
358
359 i.completionDeliveryMu.Lock()
360 if i.completionDeliveryRequest {
361 i.completionDeliveryMu.Unlock()
362 continue
363 }
364 i.completionDeliveryRunning = false
365 i.completionDeliveryMu.Unlock()
366 return
367 }
368}
369func autoSubagentsAddenda(cfg InteractiveConfig, orchestrating bool) []string {
370 addenda := make([]string, 0, 2)
371 if cfg.ResidentManager != nil && autoSubagentsToolAllowedConfig(cfg) {
372 if addendum := strings.TrimSpace(cfg.SubagentsSystemAddendum); addendum != "" {
373 addenda = append(addenda, addendum)
374 }
375 }
376 if !orchestrating {
377 if cfg.ResidentManager != nil && autoSubagentsAnyToolAllowedConfig(cfg) {
378 if addendum := strings.TrimSpace(cfg.OnDemandSubagentsSystemAddendum); addendum != "" {
379 addenda = append(addenda, addendum)
380 }
381 }
382 return addenda
383 }
384
385 if addendum := strings.TrimSpace(cfg.AutoSubagentsSystemAddendum); addendum != "" {
386 addenda = append(addenda, addendum)
387 }
388 return addenda
389}
390func removeLastAutoSubagentsAddendum(system, addendum string) (string, bool) {
391 idx := strings.LastIndex(system, addendum)
392 if idx < 0 {
393 return system, false
394 }
395 return system[:idx] + system[idx+len(addendum):], true
396}
397func (i *Interactive) applyAutoSubagentsSystemPrompt(orchestrating bool) {
398 // i.mu is sufficient here: this path updates the existing agent's system
399 // prompt and managed addenda in place; it does not replace the agent or
400 // its tool registry, so agentMu is not required.
401 i.mu.Lock()
402 defer i.mu.Unlock()
403 if i.agent == nil {
404 return
405 }
406
407 sys, _ := i.agent.PromptConfig()
408 changed := false
409 if guidance := strings.TrimSpace(i.cfg.WritingGuidance); guidance != "" {
410 var removed bool
411 sys, removed = removeLastAutoSubagentsAddendum(sys, guidance)
412 changed = changed || removed
413 }
414 for idx := len(i.managedAutoSubagentsAddenda) - 1; idx >= 0; idx-- {
415 var removed bool
416 sys, removed = removeLastAutoSubagentsAddendum(sys, i.managedAutoSubagentsAddenda[idx])
417 changed = changed || removed
418 }
419 i.managedAutoSubagentsAddenda = nil
420
421 addenda := autoSubagentsAddenda(i.cfg, orchestrating)
422 if changed {
423 sys = strings.TrimRight(sys, "\n")
424 }
425 for _, addendum := range addenda {
426 if sys != "" {
427 sys += "\n\n"
428 }
429 sys += addendum
430 i.managedAutoSubagentsAddenda = append(i.managedAutoSubagentsAddenda, addendum)
431 changed = true
432 }
433 if guidance := strings.TrimSpace(i.cfg.WritingGuidance); guidance != "" {
434 if sys != "" {
435 sys += "\n\n"
436 }
437 sys += guidance
438 changed = true
439 }
440 if !changed {
441 return
442 }
443 i.agent.SetSystemPrompt(sys)
444}
445func (i *Interactive) autoSubagentsAvailable() bool {
446 return i.cfg.ResidentManager != nil && autoSubagentsAnyToolAllowedConfig(i.cfg)
447}
448func (i *Interactive) autoSubagentsUnavailableHint() string {
449 var hints []string
450 if i.cfg.ResidentManager == nil {
451 hints = append(hints, "resident subagent manager is unavailable in this mode")
452 }
453 if !autoSubagentsAnyToolAllowedConfig(i.cfg) {
454 hints = append(hints, "launch-time tool policy excludes every subagent action")
455 }
456 return strings.Join(hints, "; ")
457}
458func autoSubagentsToolAllowedConfig(cfg InteractiveConfig) bool {
459 return cfg.AutoSubagentsToolAllowed == nil || *cfg.AutoSubagentsToolAllowed
460}
461func autoSubagentsStatusToolAllowedConfig(cfg InteractiveConfig) bool {
462 if cfg.AutoSubagentsStatusToolAllowed != nil {
463 return *cfg.AutoSubagentsStatusToolAllowed
464 }
465 // Preserve the old single-boolean embedding contract: when callers have
466 // not supplied the new field, status follows the existing delegation gate.
467 return autoSubagentsToolAllowedConfig(cfg)
468}
469func autoSubagentsStopToolAllowedConfig(cfg InteractiveConfig) bool {
470 if cfg.AutoSubagentsStopToolAllowed != nil {
471 return *cfg.AutoSubagentsStopToolAllowed
472 }
473 return autoSubagentsToolAllowedConfig(cfg)
474}
475func autoSubagentsResumeToolAllowedConfig(cfg InteractiveConfig) bool {
476 if cfg.AutoSubagentsResumeToolAllowed != nil {
477 return *cfg.AutoSubagentsResumeToolAllowed
478 }
479 return autoSubagentsToolAllowedConfig(cfg)
480}
481func autoSubagentsAnyToolAllowedConfig(cfg InteractiveConfig) bool {
482 return autoSubagentsToolAllowedConfig(cfg) ||
483 autoSubagentsStatusToolAllowedConfig(cfg) ||
484 autoSubagentsStopToolAllowedConfig(cfg) ||
485 autoSubagentsResumeToolAllowedConfig(cfg)
486}
487func (i *Interactive) autoSubagentsToolAllowed() bool {
488 return autoSubagentsToolAllowedConfig(i.cfg)
489}
490func (i *Interactive) autoSubagentsStatusToolAllowed() bool {
491 return autoSubagentsStatusToolAllowedConfig(i.cfg)
492}
493func (i *Interactive) autoSubagentsStopToolAllowed() bool {
494 return autoSubagentsStopToolAllowedConfig(i.cfg)
495}
496func (i *Interactive) autoSubagentsResumeToolAllowed() bool {
497 return autoSubagentsResumeToolAllowedConfig(i.cfg)
498}
499func (i *Interactive) autoSubagentsEnabledLocked() bool {
500 return i.cfg.AutoSubagentsEnabled != nil && *i.cfg.AutoSubagentsEnabled && i.autoSubagentsAvailable()
501}
502func (i *Interactive) applyAutoSubagentsTool() {
503 i.agentMu.Lock()
504 defer i.agentMu.Unlock()
505 i.mu.Lock()
506 defer i.mu.Unlock()
507 if i.agent == nil {
508 return
509 }
510 current := i.agent.ToolsSnapshot()
511 next := core.Registry{}
512 for name, t := range current {
513 if name == tools.SubagentToolName {
514 continue
515 }
516 next[name] = t
517 }
518 if i.autoSubagentsAvailable() {
519 facade := &tools.SubagentTool{}
520 if i.autoSubagentsToolAllowed() {
521 facade.Spawn = &tools.SubagentSpawnTool{
522 ResidentManager: i.cfg.ResidentManager,
523 BuildResidentSpec: i.cfg.BuildResidentSpec,
524 Enabled: func() bool { return true },
525 DefaultModel: func() string { return i.cfg.Model },
526 DefaultProvider: func() string { return i.cfg.Provider },
527 DefaultReasoning: func() string { return i.cfg.Reasoning },
528 ResolveSubagent: i.cfg.ResolveSubagent,
529 }
530 }
531 if i.autoSubagentsStatusToolAllowed() {
532 facade.Status = &tools.SubagentStatusTool{
533 ResidentManager: i.cfg.ResidentManager,
534 Enabled: func() bool { return true },
535 }
536 }
537 if i.autoSubagentsStopToolAllowed() {
538 facade.Stop = &tools.SubagentStopTool{
539 ResidentManager: i.cfg.ResidentManager,
540 Enabled: func() bool { return true },
541 }
542 }
543 if i.autoSubagentsResumeToolAllowed() {
544 facade.Resume = &tools.SubagentResumeTool{
545 ResidentManager: i.cfg.ResidentManager,
546 Enabled: func() bool { return true },
547 }
548 }
549 next[facade.Name()] = facade
550 }
551 i.agent.SetTools(next)
552}
553func (i *Interactive) applyTelegramTools(active bool) {
554 if active {
555 // The child ceiling must be in place even when no live main agent exists,
556 // and before Bridge.Start can accept an external prompt.
557 i.setWebSearchAvailable(false)
558 }
559 i.agentMu.Lock()
560 defer i.agentMu.Unlock()
561 i.mu.Lock()
562 defer i.mu.Unlock()
563 if i.agent == nil {
564 return
565 }
566 current := i.agent.ToolsSnapshot()
567 next := core.Registry{}
568 for name, t := range current {
569 if name == "telegram_send_image" || name == "telegram_send_file" {
570 continue
571 }
572 if active && tools.IsWebCapabilityName(name) {
573 // External Telegram prompts have no per-request confirmation
574 // surface, so V1 does not expose public-web navigation while paired.
575 continue
576 }
577 next[name] = t
578 }
579 if active {
580 sender := telegramSenderAdapter{bridge: i.telegramBridge}
581 next["telegram_send_image"] = &tools.TelegramSendImageTool{
582 CWD: i.cfg.CWD, Sandbox: i.cfg.Sandbox, Sender: sender,
583 }
584 next["telegram_send_file"] = &tools.TelegramSendFileTool{
585 CWD: i.cfg.CWD, Sandbox: i.cfg.Sandbox, Sender: sender,
586 }
587 }
588 i.agent.SetTools(next)
589 _, webSearchAvailable := next["web_search"]
590 i.setWebSearchAvailable(webSearchAvailable && !active)
591}
592func (i *Interactive) telegramStatus() {
593 var msg string
594 if i.telegramBridge != nil && i.telegramBridge.Active() {
595 s := i.telegramBridge.State()
596 msg = "telegram: connected (tui bridge)"
597 if s.Username != "" {
598 msg += " as @" + s.Username
599 }
600 if s.PairedID != 0 {
601 msg += fmt.Sprintf(" - paired with user %d", s.PairedID)
602 } else {
603 msg += " - awaiting pairing"
604 }
605 } else if pid, alive, _ := telegram.IsRunning(i.cfg.ZutHome); alive && pid > 0 {
606 msg = fmt.Sprintf("telegram: background daemon running (pid %d) - /telegram connect won't work until you stop it", pid)
607 } else {
608 cfg, _ := telegram.LoadConfig(i.cfg.ZutHome)
609 if cfg.BotToken == "" {
610 msg = "telegram: not configured. run `zut telegram-bot setup` first."
611 } else {
612 msg = "telegram: disconnected"
613 if cfg.BotUsername != "" {
614 msg += " (@" + cfg.BotUsername + " ready to connect)"
615 }
616 }
617 }
618 i.mu.Lock()
619 i.statusOK = msg
620 i.statusErr = ""
621 i.mu.Unlock()
622 i.invalidate()
623}
624func (h *telegramHost) SubmitOrQueue(prompt string, images []provider.ImageBlock) {
625 h.iv.SubmitOrQueue(prompt, images)
626}
627func (h *telegramHost) CancelTurn() { h.iv.CancelTurn() }
628func (h *telegramHost) Status() string {
629 h.iv.mu.Lock()
630 providerName := h.iv.cfg.Provider
631 model := h.iv.cfg.Model
632 cwd := h.iv.cfg.CWD
633 usage := h.iv.cumUsage
634 subscription := h.iv.cfg.AuthMethod == "oauth"
635 ctxUsed := h.iv.lastCtxInput
636 busy := h.iv.busy
637 queued := len(h.iv.queued)
638 h.iv.mu.Unlock()
639
640 ctxMax := 0
641 if m, err := provider.FindModel(providerName, model); err == nil {
642 ctxMax = m.ContextWindow
643 }
644 return telegram.FormatStatus(telegram.StatusSnapshot{
645 Provider: providerName,
646 Model: model,
647 CWD: cwd,
648 Usage: usage,
649 Subscription: subscription,
650 ContextUsed: ctxUsed,
651 ContextMax: ctxMax,
652 Busy: busy,
653 Queued: queued,
654 })
655}
656func (h *telegramHost) Notify(level, message string) {
657 h.iv.mu.Lock()
658 switch level {
659 case "error", "warn":
660 h.iv.statusErr = message
661 h.iv.statusOK = ""
662 default:
663 h.iv.statusOK = message
664 h.iv.statusErr = ""
665 }
666 h.iv.mu.Unlock()
667 h.iv.invalidate()
668}
669func (i *Interactive) openSessionOpsDialog() {
670 items := []sessionOpsItem{
671 {label: "export", action: "export", hint: "write the current session to a .zutsession file"},
672 {label: "import", action: "import", hint: "load a .zutsession file into this directory"},
673 {label: "fork", action: "fork", hint: "branch from a past user message into a new session"},
674 {label: "tree", action: "tree", hint: "switch between branches in this directory"},
675 }
676 i.sessionOpsDialog.Open(items)
677 i.invalidate()
678}
679func (i *Interactive) doSessionOp(action, arg string) {
680 switch action {
681 case "export":
682 i.doSessionExport(arg)
683 case "import":
684 i.doSessionImport(arg)
685 case "fork":
686 i.doSessionFork()
687 case "tree":
688 i.doSessionTree()
689 default:
690 i.mu.Lock()
691 i.statusErr = "unknown /session action: " + action + " (use export, import, fork, or tree)"
692 i.mu.Unlock()
693 i.invalidate()
694 }
695}
696func (i *Interactive) doSessionExport(dst string) {
697 src := i.currentSessionPath()
698 if src == "" {
699 i.mu.Lock()
700 i.statusErr = "export: no session is active (running with --no-session?)"
701 i.mu.Unlock()
702 i.invalidate()
703 return
704 }
705 // Persist any in-memory agent messages to the session file so
706 // the export carries the full conversation. Without this, the
707 // default lazy-flush-at-exit strategy leaves most of a running
708 // session unwritten and the export ends up with only the meta.
709 if i.cfg.FlushSession != nil {
710 i.cfg.FlushSession()
711 }
712 dst = unquotePath(dst)
713 if dst == "" {
714 dst = defaultExportDir()
715 } else {
716 dst = expandTilde(dst)
717 }
718 out, err := core.ExportSession(src, dst)
719 if err != nil {
720 i.mu.Lock()
721 i.statusErr = "export: " + err.Error()
722 i.mu.Unlock()
723 i.invalidate()
724 return
725 }
726 i.mu.Lock()
727 i.statusOK = "exported session to " + friendlyPath(out)
728 i.statusErr = ""
729 i.mu.Unlock()
730 i.invalidate()
731}
732func (i *Interactive) doSessionImport(src string) {
733 src = unquotePath(src)
734 if src == "" {
735 i.mu.Lock()
736 i.statusErr = "import: pass a path — e.g. /session import ~/Downloads/work.zutsession"
737 i.mu.Unlock()
738 i.invalidate()
739 return
740 }
741 src = expandTilde(src)
742 if _, err := os.Stat(src); err != nil {
743 i.mu.Lock()
744 i.statusErr = "import: " + err.Error()
745 i.mu.Unlock()
746 i.invalidate()
747 return
748 }
749 newPath, err := core.ImportSession(src, i.sessionsRoot(), i.cfg.CWD, i.cfg.Version)
750 if err != nil {
751 i.mu.Lock()
752 i.statusErr = "import: " + err.Error()
753 i.mu.Unlock()
754 i.invalidate()
755 return
756 }
757 if i.cfg.LoadSession == nil {
758 i.mu.Lock()
759 i.statusOK = "imported session at " + friendlyPath(newPath) + " (run /sessions to resume it)"
760 i.statusErr = ""
761 i.mu.Unlock()
762 i.invalidate()
763 return
764 }
765 i.markSessionTitleSwitching()
766 if err := i.cfg.LoadSession(newPath); err != nil {
767 i.restoreFailedSessionTitle()
768 i.mu.Lock()
769 i.statusErr = "import: load failed: " + err.Error()
770 i.mu.Unlock()
771 i.invalidate()
772 return
773 }
774 i.restoreLoadedSessionTitle()
775 state := i.restoreCurrentCompactHandoff()
776 i.mu.Lock()
777 i.statusOK = "imported and switched to session " + friendlyPath(newPath)
778 i.statusErr = ""
779 if i.agent != nil {
780 i.view.Messages = filterHiddenTranscriptMessages(i.agent.Messages())
781 i.cumUsage = i.agent.Cost()
782 last := i.agent.LastTurnUsage()
783 i.lastCtxInput = last.InputTokens + last.CacheReadTokens + last.CacheWriteTokens
784 if len(i.view.Messages) > initialResumeTailLimit {
785 i.view.TailLimit = initialResumeTailLimit
786 } else {
787 i.view.TailLimit = 0
788 }
789 i.view.InvalidateRenderCache()
790 }
791 i.mu.Unlock()
792 i.invalidate()
793 if state.reason != compactContinuationNone {
794 i.startRestoredCompactHandoff(i.runCtx)
795 }
796}
797func defaultExportDir() string {
798 home, err := os.UserHomeDir()
799 if err != nil || home == "" {
800 return os.TempDir()
801 }
802 downloads := filepath.Join(home, "Downloads")
803 if fi, err := os.Stat(downloads); err == nil && fi.IsDir() {
804 return downloads
805 }
806 return home
807}
808func expandTilde(p string) string {
809 if p == "" || p[0] != '~' {
810 return p
811 }
812 home, err := os.UserHomeDir()
813 if err != nil || home == "" {
814 return p
815 }
816 if len(p) == 1 {
817 return home
818 }
819 if p[1] == '/' || p[1] == filepath.Separator {
820 return filepath.Join(home, p[2:])
821 }
822 return p
823}
824func unquotePath(p string) string {
825 p = strings.TrimSpace(p)
826 if len(p) >= 2 {
827 first := p[0]
828 last := p[len(p)-1]
829 if (first == '\'' && last == '\'') || (first == '"' && last == '"') {
830 p = p[1 : len(p)-1]
831 }
832 }
833 return p
834}
835func friendlyPath(p string) string {
836 home, err := os.UserHomeDir()
837 if err != nil || home == "" {
838 return p
839 }
840 if strings.HasPrefix(p, home+string(filepath.Separator)) {
841 return "~" + p[len(home):]
842 }
843 return p
844}
845func (i *Interactive) doSessionFork() {
846 path := i.currentSessionPath()
847 if path == "" {
848 i.mu.Lock()
849 i.statusErr = "fork: no session is active (running with --no-session?)"
850 i.mu.Unlock()
851 i.invalidate()
852 return
853 }
854 i.mu.Lock()
855 busy := i.busy || i.shellRunning || i.compacting || i.autoCompacting || i.sessionLoading
856 queued := len(i.queued) != 0
857 ag := i.agent
858 i.mu.Unlock()
859 if busy || queued || ag == nil || ag.QueuedMessageCount() != 0 {
860 i.mu.Lock()
861 i.statusErr = "fork: wait until the current turn and queued messages finish"
862 i.mu.Unlock()
863 i.invalidate()
864 return
865 }
866 if i.cfg.FlushSession != nil {
867 i.cfg.FlushSession()
868 }
869 snapshot, err := core.ReadSessionSnapshot(path)
870 if err != nil {
871 i.mu.Lock()
872 i.statusErr = "fork: " + err.Error()
873 i.mu.Unlock()
874 i.invalidate()
875 return
876 }
877 msgs := snapshot.Messages
878 if len(msgs) == 0 {
879 i.mu.Lock()
880 i.statusErr = "fork: transcript is empty; nothing to fork from"
881 i.mu.Unlock()
882 i.invalidate()
883 return
884 }
885 i.pendingFork = true
886 i.jumpDialog.Open(msgs, "")
887 i.invalidate()
888}
889func (i *Interactive) doSessionTree() {
890 i.openSessionTree()
891}
892func (i *Interactive) applySessionTreeMessageSelection(src string, msgIdx, turnNo int, role provider.Role, prompt string) {
893 target := sessionTreeTarget{
894 SourcePath: src,
895 EffectiveIndex: msgIdx,
896 SelectionBoundary: msgIdx + 1,
897 Role: role,
898 UserDraft: prompt,
899 Boundary: sessionTreeMessageBoundary,
900 }
901 if role == provider.RoleUser {
902 target.SelectionBoundary = msgIdx
903 }
904 i.applySessionTreeTarget(target, turnNo)
905}
906func (i *Interactive) applySessionTreeTarget(target sessionTreeTarget, turnNo int) {
907 // Selection is a state-changing operation too. Use the selection gate so
908 // a queued/busy turn cannot race the hidden branch or accidentally submit
909 // a provider turn while the session is being swapped. The open gate cannot
910 // be reused here because the tree dialog itself owns the keyboard.
911 if !i.canCommitSessionTreeSelection() {
912 i.setSessionTreeError("tree: session branching is not available in this build")
913 return
914 }
915 src := target.SourcePath
916 if src == "" {
917 src = i.currentSessionPath()
918 }
919 if src == "" {
920 i.setSessionTreeError("tree: no session is active")
921 return
922 }
923
924 // Read and validate the selected row before flushing or creating anything.
925 // This gives tool-call/result pairs an atomic boundary and prevents a
926 // malformed selection from changing the active session. Historical rows
927 // come from a pre-compaction segment; current rows use the effective
928 // snapshot that the running agent resumes from.
929 var msgs []provider.Message
930 var historicalSegment core.SessionHistorySegment
931 if target.Historical {
932 history, err := core.ReadSessionHistory(src)
933 if err != nil {
934 i.setSessionTreeError("tree: read selection: " + err.Error())
935 return
936 }
937 if target.HistorySegment < 0 || target.HistorySegment >= len(history.Segments) {
938 i.setSessionTreeError("tree: selected history segment is unavailable")
939 return
940 }
941 historicalSegment = history.Segments[target.HistorySegment]
942 msgs = historicalSegment.Messages
943 } else {
944 sess, current, err := core.OpenSession(src)
945 if err != nil {
946 i.setSessionTreeError("tree: read selection: " + err.Error())
947 return
948 }
949 if err := sess.Close(); err != nil {
950 i.setSessionTreeError("tree: close selection: " + err.Error())
951 return
952 }
953 msgs = current
954 }
955 selection, err := sessionTreeSelection(msgs, target)
956 if err != nil {
957 i.setSessionTreeError("tree: " + err.Error())
958 return
959 }
960 if i.cfg.FlushSession != nil {
961 i.cfg.FlushSession()
962 }
963 var newPath string
964 if target.Historical {
965 newPath, err = core.BranchSessionHiddenFromHistory(src, i.sessionsRoot(), i.cfg.CWD, i.cfg.Version, historicalSegment, selection.upTo)
966 } else {
967 newPath, err = core.BranchSessionHidden(src, i.sessionsRoot(), i.cfg.CWD, i.cfg.Version, selection.upTo)
968 }
969 if err != nil {
970 i.setSessionTreeError("tree: " + err.Error())
971 return
972 }
973 i.markSessionTitleSwitching()
974 if err := i.cfg.LoadSession(newPath); err != nil {
975 i.restoreFailedSessionTitle()
976 i.setSessionTreeError("tree: checkout failed: " + err.Error())
977 return
978 }
979 state := i.restoreCurrentCompactHandoff()
980
981 // LoadSession is intentionally the old func(string) error callback: the
982 // CLI and embedders already own agent/session swapping. Refresh the view
983 // from the swapped agent here instead of requiring a new callback result.
984 i.resetSessionTitleForFreshBranch()
985 i.scrollToBottom()
986 i.mu.Lock()
987 i.lastCtxInput = 0
988 if i.agent != nil {
989 i.view.Messages = filterHiddenTranscriptMessages(i.agent.Messages())
990 i.cumUsage = i.agent.Cost()
991 last := i.agent.LastTurnUsage()
992 i.lastCtxInput = last.InputTokens + last.CacheReadTokens + last.CacheWriteTokens
993 i.view.InvalidateRenderCache()
994 }
995 i.toolCalls = map[string]*tui.ToolCallView{}
996 i.toolOrder = nil
997 i.stream.Reset()
998 i.extNotes = nil
999 if selection.restoreDraft {
1000 i.ed.SetValue(selection.draftText)
1001 i.clipboardImages = selection.images
1002 i.statusOK = fmt.Sprintf("checked out before turn %d; edit and send to branch", turnNo)
1003 } else {
1004 i.ed.Clear()
1005 i.clipboardImages = nil
1006 i.statusOK = fmt.Sprintf("checked out turn %d into a new branch", turnNo)
1007 }
1008 i.statusErr = ""
1009 i.mu.Unlock()
1010 i.scrollToBottom()
1011 // Selection does not submit, start, or queue the restored user draft; only
1012 // a later explicit Enter does that. An inherited compact handoff may resume
1013 // its hidden continuation below when this branch has the complete effective
1014 // transcript, without submitting the restored draft.
1015 i.invalidate()
1016 if state.reason != compactContinuationNone {
1017 i.startRestoredCompactHandoff(i.runCtx)
1018 }
1019}
1020func (i *Interactive) applyForkSelection(msgIdx int) {
1021 i.pendingFork = false
1022 src := i.currentSessionPath()
1023 if src == "" {
1024 i.mu.Lock()
1025 i.statusErr = "fork: no session is active"
1026 i.mu.Unlock()
1027 i.invalidate()
1028 return
1029 }
1030 if i.cfg.FlushSession != nil {
1031 i.cfg.FlushSession()
1032 }
1033 // msgIdx is 0-indexed message position; copy msgIdx+1 rows so
1034 // the selected user message is included.
1035 upTo := msgIdx + 1
1036 newPath, err := core.BranchSession(src, i.sessionsRoot(), i.cfg.CWD, i.cfg.Version, upTo)
1037 if err != nil {
1038 i.mu.Lock()
1039 i.statusErr = "fork: " + err.Error()
1040 i.mu.Unlock()
1041 i.invalidate()
1042 return
1043 }
1044 if i.cfg.LoadSession == nil {
1045 i.mu.Lock()
1046 i.statusOK = "forked at message " + formatInt(upTo) + " (run /sessions to resume)"
1047 i.statusErr = ""
1048 i.mu.Unlock()
1049 i.invalidate()
1050 return
1051 }
1052 i.markSessionTitleSwitching()
1053 if err := i.cfg.LoadSession(newPath); err != nil {
1054 i.restoreFailedSessionTitle()
1055 i.mu.Lock()
1056 i.statusErr = "fork: switch failed: " + err.Error()
1057 i.mu.Unlock()
1058 i.invalidate()
1059 return
1060 }
1061 state := i.restoreCurrentCompactHandoff()
1062 i.resetSessionTitleForFreshBranch()
1063 i.mu.Lock()
1064 i.statusOK = "forked and switched to new branch at " + friendlyPath(newPath)
1065 i.statusErr = ""
1066 i.mu.Unlock()
1067 i.invalidate()
1068 if state.reason != compactContinuationNone {
1069 i.startRestoredCompactHandoff(i.runCtx)
1070 }
1071}
1072func formatInt(n int) string {
1073 return fmt.Sprintf("%d", n)
1074}
1075func (i *Interactive) resetTranscriptRenderLocked() {
1076 i.view.InvalidateRenderCache()
1077 i.chatCacheValid = false
1078 i.prevChatLen = 0
1079 i.prevChatCols = 0
1080 i.prevChatRows = 0
1081 i.prevScrollOffset = 0
1082 i.requestRendererInvalidate()
1083}
1084func (i *Interactive) assistantMessageSideEffects(m provider.Message) {
1085 if i.cfg.OnAssistant != nil {
1086 i.cfg.OnAssistant(m)
1087 }
1088 if i.telegramBridge != nil && i.telegramBridge.Active() {
1089 var sb strings.Builder
1090 for _, c := range m.Content {
1091 if tb, ok := c.(provider.TextBlock); ok {
1092 if sb.Len() > 0 {
1093 sb.WriteString("\n")
1094 }
1095 sb.WriteString(tb.Text)
1096 }
1097 }
1098 if text := sb.String(); strings.TrimSpace(text) != "" {
1099 go i.telegramBridge.OnAssistantText(text)
1100 }
1101 }
1102}