1package modes
2
3import (
4 "context"
5 "fmt"
6 "strings"
7
8 agenttools "github.com/bnema/zut/packages/agent/tools"
9 "github.com/bnema/zut/packages/core"
10 "github.com/bnema/zut/packages/provider"
11)
12
13const goalContinueMetaKey = "zut_goal_continue"
14
15func (i *Interactive) goalUpdatesAvailable() bool {
16 ag := i.Agent()
17 if ag == nil {
18 return false
19 }
20 _, ok := ag.ToolsSnapshot()[agenttools.UpdateGoalToolName]
21 return ok
22}
23
24func (i *Interactive) goalContinuationMessage() (provider.Message, bool) {
25 if i.cfg.CurrentGoal == nil || !i.goalUpdatesAvailable() {
26 return provider.Message{}, false
27 }
28 goal := i.cfg.CurrentGoal()
29 if goal == nil || goal.Status != core.GoalActive || strings.TrimSpace(goal.Objective) == "" {
30 return provider.Message{}, false
31 }
32 text := goal.Objective +
33 "\n\nContinue working autonomously toward this active goal. Do not stop at a progress update. Continue until the goal is complete or blocked, then call update_goal."
34 if goal.MissionID != "" {
35 text += " When setting a next goal, use mission_id " + goal.MissionID + " and keep it within the same user mission."
36 }
37 return provider.Message{
38 Role: provider.RoleUser,
39 Content: []provider.Content{provider.TextBlock{Text: text}},
40 Meta: map[string]string{goalContinueMetaKey: "true"},
41 }, true
42}
43
44func (i *Interactive) goalIdleLocked() bool {
45 return !i.busy && i.agent != nil && len(i.queued) == 0 && i.agent.QueuedMessageCount() == 0
46}
47
48func (i *Interactive) goalContinuationIfIdle() (provider.Message, bool) {
49 message, ok := i.goalContinuationMessage()
50 if !ok {
51 return provider.Message{}, false
52 }
53 i.mu.Lock()
54 defer i.mu.Unlock()
55 if !i.goalIdleLocked() {
56 return provider.Message{}, false
57 }
58 return message, true
59}
60
61func (i *Interactive) requestGoalContinuationIfIdle(parent context.Context) bool {
62 message, ok := i.goalContinuationMessage()
63 if !ok || i.coordinatorHasPendingWorkers() {
64 return false
65 }
66 i.mu.Lock()
67 if !i.goalIdleLocked() {
68 i.mu.Unlock()
69 return false
70 }
71 i.busy = true
72 i.mu.Unlock()
73 i.startGoalContinuation(parent, message)
74 return true
75}
76
77func (i *Interactive) startGoalContinuation(parent context.Context, message provider.Message) {
78 goalMessage, goalActive := i.goalContinuationMessage()
79 i.mu.Lock()
80 ag := i.agent
81 if ag == nil {
82 i.busy = false
83 pendingIdleWork := i.takePendingIdleWorkLocked()
84 i.mu.Unlock()
85 runPendingIdleWork(pendingIdleWork)
86 i.invalidate()
87 return
88 }
89 if len(i.queued) > 0 {
90 next := i.queued[0]
91 i.queued = i.queued[1:]
92 i.mu.Unlock()
93 i.startTurn(parent, next)
94 return
95 }
96 if ag.QueuedMessageCount() > 0 {
97 i.mu.Unlock()
98 i.startTurnRequest(parent, "", nil, true, false)
99 return
100 }
101 if !goalActive || userMessageText(goalMessage) != userMessageText(message) {
102 i.busy = false
103 pendingIdleWork := i.takePendingIdleWorkLocked()
104 i.mu.Unlock()
105 runPendingIdleWork(pendingIdleWork)
106 // The objective may have been replaced while the prior turn was
107 // finishing. Re-evaluate it now instead of waiting for another event;
108 // the idle gate still gives queued user work priority.
109 i.requestGoalContinuationIfIdle(parent)
110 i.invalidate()
111 return
112 }
113 i.mu.Unlock()
114 ag.AppendUserContext(userMessageText(message), message.Meta)
115
116 // Persistence callbacks run synchronously from AppendUserContext, so never
117 // hold the TUI mutex across it. Re-check user work that may have arrived
118 // while the hidden continuation was being persisted.
119 i.mu.Lock()
120 if len(i.queued) > 0 {
121 next := i.queued[0]
122 i.queued = i.queued[1:]
123 i.mu.Unlock()
124 i.startTurn(parent, next)
125 return
126 }
127 i.mu.Unlock()
128 i.startTurnRequest(parent, "", nil, true, false)
129}
130
131func copySessionGoal(goal *core.SessionGoal) *core.SessionGoal {
132 if goal == nil {
133 return nil
134 }
135 copyGoal := *goal
136 return ©Goal
137}
138
139func (i *Interactive) updateActiveGoal(status core.GoalStatus, reason string) {
140 if i.cfg.CurrentGoal == nil || i.cfg.PersistGoal == nil {
141 return
142 }
143 goal := copySessionGoal(i.cfg.CurrentGoal())
144 if goal == nil || goal.Status != core.GoalActive {
145 return
146 }
147 goal.Status = status
148 goal.Reason = reason
149 if err := i.cfg.PersistGoal(goal); err != nil {
150 i.ReportError(fmt.Errorf("persist goal: %w", err))
151 return
152 }
153 i.setGoalStatus(goal)
154}
155
156func (i *Interactive) runGoalCommand(ctx context.Context, cmd string, parts []string) {
157 if i.cfg.CurrentGoal == nil || i.cfg.PersistGoal == nil {
158 i.setGoalCommandError("goal: session persistence is unavailable")
159 return
160 }
161
162 current := copySessionGoal(i.cfg.CurrentGoal())
163 if len(parts) == 2 && strings.EqualFold(parts[1], "history") {
164 if i.cfg.CurrentGoalHistory == nil {
165 i.setGoalCommandError("goal: history is unavailable")
166 return
167 }
168 history := i.cfg.CurrentGoalHistory()
169 if len(history) == 0 {
170 i.setGoalCommandStatus("no goal history")
171 return
172 }
173 entries := make([]string, 0, len(history))
174 for _, goal := range history {
175 owner := goal.Owner
176 if owner == "" {
177 owner = core.GoalOwnerUser
178 }
179 entry := fmt.Sprintf("%s (%s): %s", goal.Status, owner, goal.Objective)
180 if goal.Reason != "" {
181 entry += " (" + goal.Reason + ")"
182 }
183 entries = append(entries, entry)
184 }
185 i.setGoalCommandStatus("goal history: " + strings.Join(entries, " → "))
186 return
187 }
188 if len(parts) == 1 {
189 if current == nil {
190 i.setGoalCommandStatus("no autonomous goal")
191 return
192 }
193 owner := current.Owner
194 if owner == "" {
195 owner = core.GoalOwnerUser
196 }
197 status := fmt.Sprintf("goal %s (%s): %s", current.Status, owner, current.Objective)
198 if current.Reason != "" {
199 status += " (" + current.Reason + ")"
200 }
201 i.setGoalCommandStatus(status)
202 return
203 }
204
205 startIfIdle := false
206 startTitle := false
207 arg := ""
208 if len(parts) == 2 {
209 arg = strings.ToLower(parts[1])
210 }
211 switch arg {
212 case "pause":
213 if current == nil {
214 i.setGoalCommandError("goal: no goal to pause")
215 return
216 }
217 current.Status = core.GoalPaused
218 current.Reason = ""
219 case "resume":
220 if current == nil {
221 i.setGoalCommandError("goal: no goal to resume")
222 return
223 }
224 current.Status = core.GoalActive
225 current.Reason = ""
226 startIfIdle = true
227 case "clear":
228 if err := i.cfg.PersistGoal(nil); err != nil {
229 i.setGoalCommandError("goal: " + err.Error())
230 return
231 }
232 i.setGoalStatus(nil)
233 i.setGoalCommandStatus("autonomous goal cleared")
234 return
235 default:
236 objective := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(cmd), parts[0]))
237 if objective == "" {
238 i.setGoalCommandError("usage: /goal <objective>|pause|resume|clear|history")
239 return
240 }
241 current = &core.SessionGoal{Objective: objective, Status: core.GoalActive, Owner: core.GoalOwnerUser}
242 startIfIdle = true
243 startTitle = true
244 }
245
246 if startIfIdle && !i.goalUpdatesAvailable() {
247 i.setGoalCommandError("goal: update_goal is unavailable; enable the default tools")
248 return
249 }
250 if err := i.cfg.PersistGoal(current); err != nil {
251 i.setGoalCommandError("goal: " + err.Error())
252 return
253 }
254 i.setGoalStatus(current)
255 i.setGoalCommandStatus(fmt.Sprintf("autonomous goal %s: %s", current.Status, current.Objective))
256 if startTitle {
257 i.maybeStartSessionTitle(ctx, current.Objective)
258 }
259 if startIfIdle {
260 i.requestGoalContinuationIfIdle(ctx)
261 }
262}
263
264// RefreshGoal reloads the status badge after the CLI commits a session switch.
265func (i *Interactive) RefreshGoal() {
266 if i.cfg.CurrentGoal == nil {
267 i.setGoalStatus(nil)
268 return
269 }
270 i.setGoalStatus(i.cfg.CurrentGoal())
271}
272
273func (i *Interactive) setGoalStatus(goal *core.SessionGoal) {
274 status := core.GoalStatus("")
275 if goal != nil {
276 status = goal.Status
277 }
278 i.mu.Lock()
279 i.goalStatus = status
280 i.mu.Unlock()
281 i.invalidate()
282}
283
284func (i *Interactive) setGoalCommandStatus(message string) {
285 i.mu.Lock()
286 i.statusOK = message
287 i.statusErr = ""
288 i.mu.Unlock()
289 i.invalidate()
290}
291
292func (i *Interactive) setGoalCommandError(message string) {
293 i.mu.Lock()
294 i.statusOK = ""
295 i.statusErr = message
296 i.mu.Unlock()
297 i.invalidate()
298}