1package agent
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/bnema/zut/packages/agent/modes"
8 "github.com/bnema/zut/packages/provider"
9 "github.com/bnema/zut/packages/tui"
10)
11
12type configSettingsStore struct{}
13
14// Retain the original SettingsStore contract for model-only callers.
15func (s configSettingsStore) SetQuickModelShortcut(slot int, providerName, model string) error {
16 if slot < 1 || slot > 9 {
17 return nil
18 }
19 cfg, err := LoadConfig()
20 if err != nil {
21 return err
22 }
23 if cfg.ActiveModelProfile == slot {
24 cfg.ActiveModelProfile = 0
25 }
26 profile := modes.QuickModelShortcut{Provider: providerName, Model: model}
27 if slot <= len(cfg.QuickModelShortcuts) {
28 current := cfg.QuickModelShortcuts[slot-1]
29 profile.Reasoning = current.Reasoning
30 profile.FastMode = current.FastMode
31 }
32 return s.SetModelProfile(slot, profile, cfg.ActiveModelProfile)
33}
34
35func (configSettingsStore) SetModelProfile(slot int, profile modes.QuickModelShortcut, activeSlot int) error {
36 if slot < 1 || slot > 9 || activeSlot < 0 || activeSlot > 9 {
37 return fmt.Errorf("model profile slot must be between 1 and 9 (active may be 0)")
38 }
39 cfg, err := LoadConfig()
40 if err != nil {
41 return err
42 }
43 if len(cfg.QuickModelShortcuts) < slot {
44 next := make([]QuickModelShortcut, slot)
45 copy(next, cfg.QuickModelShortcuts)
46 cfg.QuickModelShortcuts = next
47 }
48 cfg.QuickModelShortcuts[slot-1] = QuickModelShortcut{
49 Provider: profile.Provider, Model: profile.Model,
50 Reasoning: provider.NormalizeReasoning(profile.Reasoning), FastMode: profile.FastMode,
51 }
52 cfg.ActiveModelProfile = activeSlot
53 if activeSlot == slot {
54 if profile.Provider == "" || profile.Model == "" {
55 return fmt.Errorf("cannot activate an empty model profile")
56 }
57 cfg.Provider, cfg.Model = profile.Provider, profile.Model
58 cfg.Reasoning = provider.NormalizeReasoning(profile.Reasoning)
59 fastMode := profile.FastMode
60 cfg.FastMode = &fastMode
61 }
62 // Trim trailing empty slots so config.json stays compact.
63 for len(cfg.QuickModelShortcuts) > 0 {
64 last := cfg.QuickModelShortcuts[len(cfg.QuickModelShortcuts)-1]
65 if last.Provider != "" || last.Model != "" {
66 break
67 }
68 cfg.QuickModelShortcuts = cfg.QuickModelShortcuts[:len(cfg.QuickModelShortcuts)-1]
69 }
70 return SaveConfig(cfg)
71}
72
73func (configSettingsStore) SetInlineImages(enabled bool) error {
74 cfg, err := LoadConfig()
75 if err != nil {
76 return err
77 }
78 cfg.InlineImagesEnabled = &enabled
79 return SaveConfig(cfg)
80}
81
82func (configSettingsStore) SetTerminalAlertsEnabled(enabled bool) error {
83 cfg, err := LoadConfig()
84 if err != nil {
85 return err
86 }
87 cfg.TerminalAlertsEnabled = &enabled
88 return SaveConfig(cfg)
89}
90
91func (configSettingsStore) SetTerminalTitleEnabled(enabled bool) error {
92 cfg, err := LoadConfig()
93 if err != nil {
94 return err
95 }
96 cfg.TerminalTitleEnabled = &enabled
97 return SaveConfig(cfg)
98}
99
100func (configSettingsStore) SetAutoSubagents(enabled bool) error {
101 cfg, err := LoadConfig()
102 if err != nil {
103 return err
104 }
105 cfg.AutoSubagentsEnabled = &enabled
106 return SaveConfig(cfg)
107}
108
109func (configSettingsStore) SetWebSearchEnabled(enabled bool) error {
110 cfg, err := LoadConfig()
111 if err != nil {
112 return fmt.Errorf("load config for web search setting: %w", err)
113 }
114 cfg.WebSearchEnabled = &enabled
115 if err := SaveConfig(cfg); err != nil {
116 return fmt.Errorf("save web search setting: %w", err)
117 }
118 return nil
119}
120
121func (configSettingsStore) SetFastMode(enabled bool) error {
122 cfg, err := LoadConfig()
123 if err != nil {
124 return err
125 }
126 cfg.FastMode = &enabled
127 return SaveConfig(cfg)
128}
129
130func (configSettingsStore) SetLSPEnabled(enabled bool) error {
131 cfg, err := LoadConfig()
132 if err != nil {
133 return err
134 }
135 cfg.LSPEnabled = &enabled
136 return SaveConfig(cfg)
137}
138
139func (configSettingsStore) SetSubagentLSPEnabled(enabled bool) error {
140 cfg, err := LoadConfig()
141 if err != nil {
142 return err
143 }
144 cfg.SubagentLSPEnabled = &enabled
145 return SaveConfig(cfg)
146}
147
148func (configSettingsStore) SetAutoCompactThreshold(percent int) error {
149 cfg, err := LoadConfig()
150 if err != nil {
151 return err
152 }
153 cfg.AutoCompactThreshold = &percent
154 return SaveConfig(cfg)
155}
156
157func (configSettingsStore) SetJailByDefault(enabled bool) error {
158 cfg, err := LoadConfig()
159 if err != nil {
160 return err
161 }
162 cfg.JailByDefault = &enabled
163 return SaveConfig(cfg)
164}
165
166func (configSettingsStore) SetRecursiveFileSuggest(enabled bool) error {
167 cfg, err := LoadConfig()
168 if err != nil {
169 return err
170 }
171 cfg.RecursiveFileSuggest = &enabled
172 return SaveConfig(cfg)
173}
174
175func (configSettingsStore) SetRespectGitignore(enabled bool) error {
176 cfg, err := LoadConfig()
177 if err != nil {
178 return err
179 }
180 cfg.RespectGitignore = &enabled
181 return SaveConfig(cfg)
182}
183
184func (configSettingsStore) SetCompactMode(enabled bool) error {
185 cfg, err := LoadConfig()
186 if err != nil {
187 return err
188 }
189 cfg.CompactMode = &enabled
190 return SaveConfig(cfg)
191}
192
193func (configSettingsStore) SetShowInstructionsAtStartup(enabled bool) error {
194 cfg, err := LoadConfig()
195 if err != nil {
196 return err
197 }
198 cfg.ShowInstructionsAtStartup = &enabled
199 return SaveConfig(cfg)
200}
201
202func (configSettingsStore) SetTUIInputStyle(style string) error {
203 cfg, err := LoadConfig()
204 if err != nil {
205 return err
206 }
207 style = tui.NormalizeInputStyle(style)
208 if style == tui.InputStylePlain {
209 cfg.TUIInputStyle = ""
210 } else {
211 cfg.TUIInputStyle = style
212 }
213 return SaveConfig(cfg)
214}
215
216func (configSettingsStore) SetTUIStatusPosition(position string) error {
217 cfg, err := LoadConfig()
218 if err != nil {
219 return err
220 }
221 position = tui.NormalizeStatusPosition(position)
222 if position == tui.StatusPositionAboveInput {
223 cfg.TUIStatusPosition = ""
224 } else {
225 cfg.TUIStatusPosition = position
226 }
227 return SaveConfig(cfg)
228}
229
230func (configSettingsStore) SetTUIWorkingPosition(position string) error {
231 cfg, err := LoadConfig()
232 if err != nil {
233 return err
234 }
235 position = tui.NormalizeWorkingPosition(position)
236 if position == tui.WorkingPositionAboveInput {
237 cfg.TUIWorkingPosition = ""
238 } else {
239 cfg.TUIWorkingPosition = position
240 }
241 return SaveConfig(cfg)
242}
243
244func (configSettingsStore) SetReasoning(level string) error {
245 cfg, err := LoadConfig()
246 if err != nil {
247 return err
248 }
249 cfg.Reasoning = provider.NormalizeReasoning(level)
250 return SaveConfig(cfg)
251}
252
253func (configSettingsStore) SetTheme(name string) error {
254 cfg, err := LoadConfig()
255 if err != nil {
256 return err
257 }
258 if name == "auto" || name == "inherited" {
259 name = ""
260 }
261 cfg.Theme = name
262 return SaveConfig(cfg)
263}
264
265// AutoSubagentsEnabled reads whether the interactive primary agent may
266// delegate proactively. The canonical subagent tools remain available for
267// user-requested delegation and skill-mandated workflows when disabled.
268func AutoSubagentsEnabled() bool {
269 cfg, err := LoadConfig()
270 if err != nil {
271 return false
272 }
273 return cfg.AutoSubagentsEnabled != nil && *cfg.AutoSubagentsEnabled
274}
275
276// ProactiveSubagentsRoutingAddendum is prepended to the interactive
277// collaboration contract only when launch-time policy exposes the spawn
278// action: naming a profile is meaningless when the primary cannot dispatch.
279const ProactiveSubagentsRoutingAddendum = `Route before you work:
280- Process start tells you nothing about the task or the workers it needs; routing happens when the user states the request you are about to work on.
281- Name the parts you keep on the critical path and the [subagents_list] profile that owns each delegable part, before you implement or spawn.
282- State that routing once, in the reply that starts the work, and let the tool calls that follow speak for themselves instead of narrating them.
283- Say plainly when nothing is worth delegating instead of inventing sidecars, and spawn a clearly described general worker when no profile matches a scope.`
284
285// ProactiveSubagentsSystemAddendum keeps the interactive primary agent on the
286// critical path and reserves delegation for genuinely parallel sidecar work.
287const ProactiveSubagentsSystemAddendum = `Proactive subagent delegation is enabled. You remain the primary owner and implementer of the user's task.
288
289Before delegating:
290- Form a short high-level plan and identify the immediate next task you will perform locally.
291- Delegate only a concrete, bounded sidecar that can progress independently while you perform useful local work.
292- Keep urgent, tightly coupled, or immediate blocking work local. If your next action depends on a result, do that work yourself instead of spawning and waiting for it.
293- Divide ownership by distinct question, responsibility, package, or disjoint file set. Give every worker a self-contained task.
294- If you cannot name useful non-overlapping local work, do not delegate.
295
296After delegating:
297- The worker owns its delegated scope until it completes. Continue only with the non-overlapping local task selected before delegation.
298- Do not search, read, test, review, edit, or otherwise reproduce the worker's task. You may dispatch additional workers only for genuinely distinct scopes.
299- If the user or an active workflow explicitly requires a worker to own blocking work, delegate it with required:true and end or yield your turn instead of duplicating it.
300- Integrate and, when appropriate, verify completed worker results before answering. You may apply a completed worktree patch without redoing the delegated task.`
301
302// StrictOrchestratorSystemAddendum is used only by explicit headless
303// orchestration. The parent coordinates workers and never becomes an
304// implementer itself.
305const StrictOrchestratorSystemAddendum = `Strict subagent orchestration is enabled. You are the primary-agent orchestrator, not an implementer.
306
307- Use read, grep, and ast only for read-only codebase exploration before dispatching work. Prefer ast when the question depends on source syntax. Use web_search only for public-web research that improves worker task instructions.
308- Divide the request into concrete, bounded, non-overlapping worker scopes before dispatching. Delegate all implementation, debugging/testing, and code-review work to an appropriately named subagent profile or a clearly described general worker.
309- Do not write or edit code yourself, make direct implementation tool calls, inspect or review code through implementation tools, or apply worker patches. You may use read, grep, ast, and web_search for the read-only research above and review worker reports.
310- Once a worker is active, do not investigate or perform its delegated scope. Only coordinate workers, dispatch additional disjoint work, or end or yield the turn.
311- Give every worker a self-contained task and synthesize the results.`
312
313const subagentLifecycleAddendum = `Workers start without this conversation's context. Shared-worktree workers edit the same working directory, so coordinate dependent work and avoid conflicting edits. Use isolation:"worktree" for parallel coding when workers need separate trees; its changes are returned as a patch and never applied automatically. Do not invent feature scope beyond the user's request. Child workers cannot recursively spawn more sub-agents in v1.
314
315Use required:true whenever your answer or a declared workflow depends on that worker, especially for required validation or finalization. Required workers remain asynchronous unless you explicitly set the wait field on a spawn or resume action: without it, manager calls return immediately, the parent stays free to coordinate or perform policy-permitted non-overlapping work, and the host delivers terminal outcomes through completion updates. Failed, canceled, or interrupted required work remains unmet: use an enabled manager follow-up action to retry it and do not claim completion. An indeterminate outcome after host restart must not be retried automatically; the user must inspect durable results and side effects, then explicitly resume or restart the worker with a new prompt. Required work has no automatic waiver path. Keep required:false only for independent work that may safely finish later.
316
317Completion is host-event-driven unless you explicitly set the wait field on a spawn or resume action to a whole number of seconds (1–300): on spawn it bounds the initial task, and on resume it bounds the follow-up turn. Omitting wait always returns immediately. An expired wait leaves the accepted child active, whether queued or running; do not retry it until terminal failure, cancellation, or interruption. Never use "bash sleep", "watch", "tail -f", polling loops, repeated "status" calls, or dashboard, metadata, or file checks solely to wait. Those are not completion signals. Continue only with genuinely non-overlapping work; otherwise end or yield your turn until the host injects a completion update.
318
319When workers finish, use the host update's agent ID, status, task, optional error, and final response or tail to coordinate any follow-up and summarize the outcome. Treat [auto-subagents update] and [required-subagents update] messages as observed worker state, not as new user requests.`
320
321// OnDemandSubagentsSystemAddendum keeps the canonical subagent tools
322// available without enabling proactive delegation.
323const OnDemandSubagentsSystemAddendum = `Subagent tools are available only when the user asks you to delegate and the relevant launch-time tool permission allows it, or an active skill workflow requires delegation. Use them only in those cases. A worker owns its delegated scope until completion: do not repeat that work in the parent. Continue only with a concrete non-overlapping task selected before spawning; if delegation owns the blocking task, end or yield the parent turn instead.
324
325Mark delegated work required:true when the user's request or workflow requires its outcome before completion. Omit the wait field on a spawn or resume action to return immediately and receive completion through a host update. Set wait only to an explicit 1–300 second value when you need to wait for that task or follow-up turn; an expired wait leaves the accepted child active, whether queued or running. Do not retry it until terminal failure, cancellation, or interruption. Failed, canceled, or interrupted required work remains unmet until a successful follow-up; after host restart, an indeterminate outcome requires user-directed reconciliation of durable results and side effects before non-idempotent work is retried. Do not produce a terminal answer until required work is satisfied. Required work has no automatic waiver path. Do not delegate proactively or switch into an orchestrator role; otherwise perform the work yourself.`
326
327const StrictOrchestratorDelegationUnavailableAddendum = `Delegation is unavailable in this session because the launch-time tool policy does not expose the subagent spawn action. Remain the primary-agent orchestrator: report this limitation to the user rather than implementing, debugging/testing, or reviewing directly, and end or yield your turn until delegation is available. Do not treat the status action or other tools as a substitute for spawning.`
328
329const ProactiveSubagentsDelegationUnavailableAddendum = `Proactive delegation is unavailable in this session because the launch-time tool policy does not expose the subagent spawn action. Continue the user's task locally; do not report delegation as a blocker.`
330
331// SubagentActions records which subagent actions the launch-time tool policy
332// exposes, so prompt guidance names only actions the model can call.
333type SubagentActions struct {
334 Spawn, Stop, Resume, Interrupt bool
335}
336
337func (a SubagentActions) lifecycle() bool { return a.Stop || a.Resume || a.Interrupt }
338
339// ProactiveSubagentsSystemAddendumFor returns the interactive collaboration
340// contract with guidance only for manager actions exposed at launch time.
341func ProactiveSubagentsSystemAddendumFor(actions SubagentActions) string {
342 base := ProactiveSubagentsSystemAddendum
343 if actions.Spawn {
344 base = ProactiveSubagentsRoutingAddendum + "\n\n" + base
345 }
346 return subagentsSystemAddendumFor(base, ProactiveSubagentsDelegationUnavailableAddendum, false, actions)
347}
348
349// StrictOrchestratorSystemAddendumFor returns the headless manager-only
350// contract with guidance only for manager actions exposed at launch time.
351func StrictOrchestratorSystemAddendumFor(actions SubagentActions) string {
352 return subagentsSystemAddendumFor(StrictOrchestratorSystemAddendum, StrictOrchestratorDelegationUnavailableAddendum, true, actions)
353}
354
355func subagentsSystemAddendumFor(base, unavailable string, strict bool, actions SubagentActions) string {
356 addendum := base + "\n\n" + subagentLifecycleAddendum
357 var lifecycle []string
358 if actions.Resume {
359 lifecycle = append(lifecycle, "use resume with an agent id and follow-up prompt to continue an idle worker, steer a running worker mid-turn, or restart a stopped worker with its existing session context")
360 }
361 if actions.Interrupt {
362 lifecycle = append(lifecycle, "use interrupt to cancel only a worker's running turn while keeping its context, for example before asking it to wrap up")
363 }
364 if actions.Stop {
365 lifecycle = append(lifecycle, "use stop to request termination of a stuck worker")
366 }
367 if len(lifecycle) != 0 {
368 addendum += "\n\nSubagent manager lifecycle actions available: " + strings.Join(lifecycle, "; ") + "."
369 }
370 if !actions.Spawn {
371 if actions.lifecycle() {
372 addendum += "\n\nSpawning new workers is unavailable in this session. Use only the enabled manager lifecycle actions for existing workers."
373 if strict {
374 addendum += " Do not implement, debug, test, or review directly."
375 } else {
376 addendum += " Continue non-delegated work locally."
377 }
378 } else {
379 addendum += "\n\n" + unavailable
380 }
381 }
382 return addendum
383}