1package agent
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/signal"
12 "path/filepath"
13 "strings"
14 "sync"
15 "syscall"
16 "time"
17
18 "github.com/patriceckhart/zot/packages/agent/extensions"
19 "github.com/patriceckhart/zot/packages/agent/extproto"
20 "github.com/patriceckhart/zot/packages/agent/modes"
21 "github.com/patriceckhart/zot/packages/agent/skills"
22 "github.com/patriceckhart/zot/packages/agent/swarm"
23 "github.com/patriceckhart/zot/packages/agent/tools"
24 "github.com/patriceckhart/zot/packages/core"
25 "github.com/patriceckhart/zot/packages/provider"
26 "github.com/patriceckhart/zot/packages/provider/auth"
27 "github.com/patriceckhart/zot/packages/tui"
28)
29
30// interactiveExtHooks is a tiny adapter that lets the extension
31// manager call back into the Interactive instance built later in
32// runInteractive. The forward-declared *modes.Interactive is filled
33// in immediately after manager construction.
34type interactiveExtHooks struct {
35 ivPtr **modes.Interactive
36}
37
38func (h *interactiveExtHooks) iv() *modes.Interactive {
39 if h == nil || h.ivPtr == nil {
40 return nil
41 }
42 return *h.ivPtr
43}
44
45func (h *interactiveExtHooks) Notify(extName, level, message string) {
46 if iv := h.iv(); iv != nil {
47 iv.Notify(extName, level, message)
48 }
49}
50func (h *interactiveExtHooks) Submit(text string) {
51 if iv := h.iv(); iv != nil {
52 iv.SubmitOrQueue(text, nil)
53 }
54}
55func (h *interactiveExtHooks) SubmitSlash(text string) {
56 if iv := h.iv(); iv != nil {
57 iv.SubmitSlash(text)
58 }
59}
60func (h *interactiveExtHooks) Insert(text string) {
61 if iv := h.iv(); iv != nil {
62 iv.Insert(text)
63 }
64}
65func (h *interactiveExtHooks) Display(extName, text string) {
66 if iv := h.iv(); iv != nil {
67 iv.Display(extName, text)
68 }
69}
70func (h *interactiveExtHooks) ClearNotes(extName string) {
71 if iv := h.iv(); iv != nil {
72 iv.ClearNotes(extName)
73 }
74}
75func (h *interactiveExtHooks) OpenPanel(extName string, spec extproto.PanelSpec) {
76 if iv := h.iv(); iv != nil {
77 iv.OpenPanel(extName, spec)
78 }
79}
80func (h *interactiveExtHooks) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
81 if iv := h.iv(); iv != nil {
82 iv.UpdatePanel(extName, panelID, title, lines, footer)
83 }
84}
85func (h *interactiveExtHooks) ClosePanel(extName, panelID string) {
86 if iv := h.iv(); iv != nil {
87 iv.ClosePanel(extName, panelID)
88 }
89}
90
91// extToolAdapter bridges *extensions.Manager to the
92// ExtensionToolSource interface declared in build.go (kept narrow to
93// avoid a build->extensions import cycle). One adapter instance per
94// run; used at every Resolve point so re-built agents pick up the
95// same set of extension tools.
96type extToolAdapter struct {
97 mgr *extensions.Manager
98}
99
100func (a *extToolAdapter) Tools() []ExtensionToolInfo {
101 infos := a.mgr.Tools()
102 out := make([]ExtensionToolInfo, len(infos))
103 for i, t := range infos {
104 out[i] = ExtensionToolInfo{
105 Extension: t.Extension,
106 Name: t.Name,
107 Description: t.Description,
108 Schema: t.Schema,
109 Deferred: t.Deferred,
110 }
111 }
112 return out
113}
114
115func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
116 return extensions.NewTool(a.mgr, extensions.ToolInfo{
117 Extension: info.Extension,
118 Name: info.Name,
119 Description: info.Description,
120 Schema: info.Schema,
121 Deferred: info.Deferred,
122 })
123}
124
125// liveInteractiveAgent returns the agent currently owned by the TUI. The
126// fallback is only used before the Interactive has been constructed.
127//
128// Agent rebuilds, such as cross-provider model switches, replace the TUI's
129// agent without replacing the startup pointer held by runInteractive. Session
130// operations must therefore resolve the live agent at the time of the action.
131func liveInteractiveAgent(iv *modes.Interactive, fallback *core.Agent) *core.Agent {
132 if iv != nil {
133 return iv.Agent()
134 }
135 return fallback
136}
137
138func trimMessagesForResume(msgs []provider.Message, keepTail int) []provider.Message {
139 if keepTail <= 0 || len(msgs) <= keepTail {
140 return provider.RepairOrphanedToolResults(msgs)
141 }
142 var out []provider.Message
143 start := len(msgs) - keepTail
144 // Preserve the synthetic compaction summary when present so an
145 // already-compacted session stays compacted after resume.
146 if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" && start > 1 {
147 out = append(out, msgs[0])
148 }
149 // Avoid hydrating a tail that starts with orphan tool_result rows;
150 // provider APIs require those to be paired with an earlier tool_use.
151 for start < len(msgs) && msgs[start].Role == provider.RoleTool {
152 start++
153 }
154 out = append(out, msgs[start:]...)
155 return provider.RepairOrphanedToolResults(out)
156}
157
158// fanoutAgentEvent translates a core.AgentEvent into the wire-format
159// EventFromHost and pushes it through the extension manager. Only
160// the events that have a clear extension-facing meaning are
161// forwarded; internal-only ones (text_delta, tool_progress) are
162// dropped to keep the per-extension stream sane.
163func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
164 if mgr == nil {
165 return
166 }
167 switch e := ev.(type) {
168 case core.EvTurnStart:
169 mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
170 case core.EvToolCall:
171 mgr.EmitEvent(extproto.EventFromHost{
172 Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
173 })
174 case core.EvAssistantMessage:
175 // Concat the visible text portions of the message; binary
176 // blocks (tool_use, etc.) are skipped because subscribers
177 // usually want a string they can grep / display.
178 var text string
179 for _, c := range e.Message.Content {
180 if tb, ok := c.(provider.TextBlock); ok {
181 text += tb.Text
182 }
183 }
184 mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
185 case core.EvTurnEnd:
186 ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
187 if e.Err != nil {
188 ev.Error = e.Err.Error()
189 }
190 mgr.EmitEvent(ev)
191 }
192}
193
194// Run is the top-level entrypoint for the zot binary.
195func Run(rawArgs []string, version string) error {
196 // Apply network configuration before any subcommand can make an HTTP
197 // request. Standard proxy environment variables retain precedence.
198 applyConfiguredHTTPProxy()
199
200 // Subcommand router: `zot bot ...` is handled separately so the
201 // generic flag parser doesn't reject "bot" as a positional arg.
202 if handled, err := runBotCommand(rawArgs, version); handled {
203 return err
204 }
205 if handled, err := runExtCommand(rawArgs, version); handled {
206 return err
207 }
208 if handled, err := runUpdateCommand(rawArgs, version); handled {
209 return err
210 }
211 if handled, err := runZotfileCommand(rawArgs, version); handled {
212 return err
213 }
214 return runWithArgsRaw(rawArgs, version)
215}
216
217func runWithArgsRaw(rawArgs []string, version string) error {
218 // `zot rpc` is shorthand for `zot --rpc` so third-party apps can
219 // spawn the binary with a clean argv. Strip the leading 'rpc'
220 // token and let the rest flow through the normal arg parser.
221 if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
222 rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
223 }
224
225 if fi, err := os.Stdin.Stat(); err == nil {
226 rawArgs = argsForStdin(rawArgs, fi.Mode())
227 }
228 args, err := ParseArgs(rawArgs)
229 if err != nil {
230 PrintHelp(version)
231 return err
232 }
233 if args.Help {
234 PrintHelp(version)
235 return nil
236 }
237 if args.Version {
238 fmt.Println("zot", version)
239 return nil
240 }
241 // Model catalog: load any cached discovery data before we inspect
242 // the model list (list-models, print/json, interactive).
243 prepareRuntimeCatalog()
244
245 if args.ListModels {
246 printModels()
247 return nil
248 }
249
250 return runWithArgs(args, version)
251}
252
253func runWithArgs(args Args, version string) error {
254 ctx := context.Background()
255 switch args.Mode {
256 case ModePrint:
257 return runPrintMode(ctx, args, version)
258 case ModeStream:
259 return runStreamMode(ctx, args, version)
260 case ModeJSON:
261 return runJSONMode(ctx, args, version)
262 case ModeRPC:
263 return runRPCMode(ctx, args, version)
264 case ModeSwarmAgent:
265 return runSwarmAgentMode(ctx, args, version)
266 default:
267 return runInteractive(ctx, args, version)
268 }
269}
270
271// ---- print / json modes: require credentials, run single-shot ----
272
273// nonInteractiveExtHooks is the HostHooks impl used by print / json
274// modes. They have no TUI, so notify / display go to stderr and
275// submit / insert are no-ops (the extension can't steer a
276// single-shot run once it's in flight anyway).
277type nonInteractiveExtHooks struct{}
278
279func (nonInteractiveExtHooks) Notify(ext, level, message string) {
280 fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
281}
282func (nonInteractiveExtHooks) Submit(string) {}
283func (nonInteractiveExtHooks) SubmitSlash(string) {}
284func (nonInteractiveExtHooks) Insert(string) {}
285func (nonInteractiveExtHooks) Display(string, string) {}
286func (nonInteractiveExtHooks) ClearNotes(string) {}
287func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec) {}
288func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
289func (nonInteractiveExtHooks) ClosePanel(string, string) {}
290
291// setupNonInteractiveExtensions loads --ext paths and (unless
292// --no-ext) runs discovery. Returns the manager so the caller can
293// wire tools into the resolved registry, and a cleanup closure to
294// defer. Mirrors the interactive-mode setup minus the TUI hooks.
295func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
296 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
297 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
298 fmt.Fprintln(os.Stderr, "extension load:", e)
299 }
300 if !args.NoExt {
301 for _, e := range extMgr.Discover(ctx) {
302 fmt.Fprintln(os.Stderr, "extension load:", e)
303 }
304 }
305 extMgr.WaitForReady(3 * time.Second)
306 r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
307 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
308 return extMgr, func() { extMgr.Stop(2 * time.Second) }
309}
310
311// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
312// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
313// interactive path wires up, so extensions get their normal
314// event-intercept surface in print / json / rpc flows too.
315func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
316 if ag == nil || extMgr == nil {
317 return
318 }
319 ag.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
320 res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
321 if res.Block {
322 return false, res.Reason, nil
323 }
324 return true, "", res.ModifiedArgs
325 }
326 ag.BeforeTurn = func(step int) (bool, string) {
327 res := extMgr.InterceptTurnStart(ctx, step)
328 return !res.Block, res.Reason
329 }
330 ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
331 res := extMgr.InterceptAssistantMessage(ctx, text)
332 if res.Block {
333 return false, res.Reason, ""
334 }
335 return true, "", res.ReplaceText
336 }
337 ag.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
338}
339
340type printStats struct {
341 Provider string `json:"provider"`
342 Model string `json:"model"`
343 PromptTokens int `json:"prompt_tokens"`
344 ReasoningTokens *int `json:"reasoning_tokens"`
345 GeneratedOutputTokens int `json:"generated_output_tokens"`
346 ElapsedMS int64 `json:"elapsed_ms"`
347}
348
349func writePrintStats(path, providerID, model string, usage provider.Usage, elapsed time.Duration) error {
350 var reasoning *int
351 generated := usage.OutputTokens
352 if usage.ReasoningTokensKnown {
353 count := usage.ReasoningTokens
354 reasoning = &count
355 generated -= count
356 if generated < 0 {
357 generated = 0
358 }
359 }
360 stats := printStats{
361 Provider: providerID,
362 Model: model,
363 PromptTokens: usage.InputTokens + usage.CacheReadTokens + usage.CacheWriteTokens,
364 ReasoningTokens: reasoning,
365 GeneratedOutputTokens: generated,
366 ElapsedMS: elapsed.Milliseconds(),
367 }
368 data, err := json.MarshalIndent(stats, "", " ")
369 if err != nil {
370 return fmt.Errorf("encode stats: %w", err)
371 }
372 data = append(data, '\n')
373 if err := os.WriteFile(path, data, 0o644); err != nil {
374 return fmt.Errorf("write stats %q: %w", path, err)
375 }
376 return nil
377}
378
379func runPrintMode(ctx context.Context, args Args, version string) error {
380 if args.NoYolo {
381 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
382 }
383 r, err := Resolve(args, true)
384 if err != nil {
385 return err
386 }
387 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
388 defer stopExt()
389
390 ag := r.NewAgent()
391 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
392 sess, _ := openOrCreateSession(args, r, ag, version)
393 defer sess.Close()
394
395 piped, _ := readAllStdin()
396 prompt := combinePromptInput(piped, args.Prompt)
397 if prompt == "" {
398 return fmt.Errorf("print mode requires a prompt (arg or stdin)")
399 }
400
401 start := len(ag.Messages())
402 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, nil, os.Stderr); err != nil {
403 return err
404 }
405 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
406 started := time.Now()
407 usage, err := modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
408 elapsed := time.Since(started)
409 WriteNewTranscript(ag, sess, start)
410 if err != nil {
411 return err
412 }
413 if args.StatsPath != "" {
414 return writePrintStats(args.StatsPath, r.Provider, r.Model, usage, elapsed)
415 }
416 return nil
417}
418
419func runStreamMode(ctx context.Context, args Args, version string) error {
420 if args.NoYolo {
421 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in stream mode (no interactive prompt available); tools will run without confirmation")
422 }
423 r, err := Resolve(args, true)
424 if err != nil {
425 return err
426 }
427 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
428 defer stopExt()
429
430 ag := r.NewAgent()
431 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
432 sess, _ := openOrCreateSession(args, r, ag, version)
433 defer sess.Close()
434
435 piped, _ := readAllStdin()
436 prompt := combinePromptInput(piped, args.Prompt)
437 if prompt == "" {
438 return fmt.Errorf("stream mode requires a prompt (arg or stdin)")
439 }
440
441 start := len(ag.Messages())
442 preSink, finishPre := newStreamTextSink(os.Stdout)
443 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
444 finishPre()
445 return err
446 }
447 finishPre()
448 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
449 err = modes.RunStream(ctx, ag, prompt, nil, os.Stdout)
450 WriteNewTranscript(ag, sess, start)
451 return err
452}
453
454func newStreamTextSink(out io.Writer) (func(core.AgentEvent), func()) {
455 var streamed, wroteText, lastWasNL bool
456 writeText := func(text string) {
457 if text == "" {
458 return
459 }
460 _, _ = fmt.Fprint(out, text)
461 if syncer, ok := out.(interface{ Sync() error }); ok {
462 _ = syncer.Sync()
463 }
464 wroteText = true
465 lastWasNL = strings.HasSuffix(text, "\n")
466 }
467 sink := func(ev core.AgentEvent) {
468 switch e := ev.(type) {
469 case core.EvAssistantStart:
470 streamed = false
471 case core.EvTextDelta:
472 streamed = true
473 writeText(e.Delta)
474 case core.EvAssistantMessage:
475 if streamed {
476 return
477 }
478 var text strings.Builder
479 for _, content := range e.Message.Content {
480 if block, ok := content.(provider.TextBlock); ok {
481 if text.Len() > 0 {
482 text.WriteString("\n")
483 }
484 text.WriteString(block.Text)
485 }
486 }
487 writeText(text.String())
488 }
489 }
490 finish := func() {
491 if wroteText && !lastWasNL {
492 writeText("\n")
493 }
494 }
495 return sink, finish
496}
497
498func runJSONMode(ctx context.Context, args Args, version string) error {
499 if args.NoYolo {
500 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
501 }
502 r, err := Resolve(args, true)
503 if err != nil {
504 return err
505 }
506 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
507 defer stopExt()
508
509 ag := r.NewAgent()
510 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
511 sess, _ := openOrCreateSession(args, r, ag, version)
512 defer sess.Close()
513
514 piped, _ := readAllStdin()
515 prompt := combinePromptInput(piped, args.Prompt)
516 if prompt == "" {
517 return fmt.Errorf("json mode requires a prompt (arg or stdin)")
518 }
519
520 start := len(ag.Messages())
521 enc := json.NewEncoder(os.Stdout)
522 preSink := func(ev core.AgentEvent) {
523 _ = enc.Encode(modes.EventToJSON(ev))
524 }
525 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
526 _ = enc.Encode(map[string]any{"type": "error", "message": err.Error()})
527 return err
528 }
529 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
530 err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
531 WriteNewTranscript(ag, sess, start)
532 return err
533}
534
535// runZotfileStartupPre runs entry.pre before the main non-interactive prompt.
536// "!command" values execute via BashTool; other values are sent as an agent turn.
537// shellOut receives live shell chunks (typically os.Stderr); sink receives
538// agent events for plain-text pre (stream mode wires a live text sink).
539func runZotfileStartupPre(ctx context.Context, pre, cwd string, sandbox *tools.Sandbox, ag *core.Agent, sink func(core.AgentEvent), shellOut io.Writer) error {
540 pre = strings.TrimSpace(pre)
541 if pre == "" {
542 return nil
543 }
544 if cmd, ok := modes.ShellEscapeCommand(pre); ok {
545 raw, err := json.Marshal(map[string]any{"command": cmd})
546 if err != nil {
547 return err
548 }
549 if shellOut != nil {
550 fmt.Fprintf(shellOut, "$ %s\n", cmd)
551 if f, ok := shellOut.(interface{ Sync() error }); ok {
552 _ = f.Sync()
553 }
554 }
555 progress := func(chunk string) {
556 if shellOut == nil || chunk == "" {
557 return
558 }
559 fmt.Fprint(shellOut, chunk)
560 if f, ok := shellOut.(interface{ Sync() error }); ok {
561 _ = f.Sync()
562 }
563 }
564 bash := &tools.BashTool{CWD: cwd, Sandbox: sandbox}
565 res, err := bash.Execute(ctx, raw, progress)
566 if err != nil {
567 return fmt.Errorf("zotfile entry.pre: %w", err)
568 }
569 if res.IsError {
570 var sb strings.Builder
571 for _, c := range res.Content {
572 if tb, ok := c.(provider.TextBlock); ok {
573 sb.WriteString(tb.Text)
574 }
575 }
576 msg := strings.TrimSpace(sb.String())
577 if msg == "" {
578 msg = "command failed"
579 }
580 return fmt.Errorf("zotfile entry.pre: %s", msg)
581 }
582 return nil
583 }
584 if ag == nil {
585 return fmt.Errorf("zotfile entry.pre requires an agent for non-shell prompts")
586 }
587 if sink == nil {
588 sink = func(core.AgentEvent) {}
589 }
590 return ag.Prompt(ctx, pre, nil, sink)
591}
592
593// refreshAgentToolsAndPrompt re-resolves tools (including rediscovered
594// skills and currently loaded extension tools) and updates the live
595// agent's registry and system prompt. Used after /reload-ext and after
596// zotfile entry.pre installs new skills or extensions.
597// mutateRegistry, if non-nil, can inject session-specific tools (e.g. swarm_spawn).
598func refreshAgentToolsAndPrompt(args Args, sharedSandbox *tools.Sandbox, extToolAdapter ExtensionToolSource, ag *core.Agent, mutateRegistry func(core.Registry) core.Registry) {
599 if ag == nil {
600 return
601 }
602 resolved, err := Resolve(args, true)
603 if err != nil {
604 return
605 }
606 if sharedSandbox != nil {
607 resolved.UseSandbox(sharedSandbox)
608 }
609 if extToolAdapter != nil {
610 resolved.MergeExtensionTools(extToolAdapter)
611 }
612 reg := resolved.ToolRegistry
613 if mutateRegistry != nil {
614 reg = mutateRegistry(reg)
615 }
616 ag.SetTools(reg)
617 ag.System = resolved.SystemPrompt
618}
619
620// reloadResourcesAfterStartupPre reloads extensions (if any) and
621// refreshes the agent tool registry + system prompt so skills/extensions
622// installed by entry.pre are visible to the following turn.
623func reloadResourcesAfterStartupPre(ctx context.Context, args Args, extMgr *extensions.Manager, sharedSandbox *tools.Sandbox, ag *core.Agent) {
624 if strings.TrimSpace(args.StartupPre) == "" || ag == nil {
625 return
626 }
627 adapter := &extToolAdapter{mgr: extMgr}
628 if extMgr != nil {
629 _ = extMgr.Reload(ctx, 2*time.Second)
630 }
631 refreshAgentToolsAndPrompt(args, sharedSandbox, adapter, ag, nil)
632}
633
634// ---- interactive mode: opens the TUI even without credentials ----
635
636func runInteractive(ctx context.Context, args Args, version string) error {
637 // Resolve WITHOUT requiring credentials.
638 r, err := Resolve(args, false)
639 if err != nil {
640 return err
641 }
642
643 authStore := AuthStoreFor()
644 mgr := auth.NewManager(authStore)
645 defer mgr.Close()
646
647 // Keep the sandbox pointer stable across agent rebuilds (login / model
648 // switch). The Interactive UI toggles the lock via this pointer, and
649 // rebuilt tool instances must share the same one so the lock sticks.
650 sharedSandbox := r.Sandbox
651
652 // Build the extension manager BEFORE the agent so we can fold
653 // extension-defined tools into the registry. Forward-declare iv so
654 // the host hooks adapter can dereference it after construction.
655 var iv *modes.Interactive
656 extHooks := &interactiveExtHooks{ivPtr: &iv}
657 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
658 var startupExtensionErrors []string
659 // --ext paths first so they win against installed extensions of
660 // the same name (loadOne's first-write-wins semantics).
661 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
662 startupExtensionErrors = append(startupExtensionErrors, e.Error())
663 }
664 // --no-ext skips the global + project-local discovery scan;
665 // explicit --ext paths above are still honoured so you can run
666 // "only this extension" with --no-ext --ext ./x.
667 if !args.NoExt {
668 for _, e := range extMgr.Discover(ctx) {
669 startupExtensionErrors = append(startupExtensionErrors, e.Error())
670 }
671 }
672 // Wait briefly for extensions to flush their initial register_tool
673 // frames before we build the agent's tool registry. Half a second
674 // is plenty for any extension that's actually well-behaved; ones
675 // that don't send a ready frame eat the full grace and proceed.
676 // 3s is the per-extension grace period for the ready frame.
677 // Native binaries are instant; runtimes like `npx tsx` take ~1.5s
678 // from cold cache. The wait is tight only for extensions that
679 // haven't sent ready by then; ones that signalled earlier release
680 // the wait immediately.
681 extMgr.WaitForReady(3 * time.Second)
682 defer extMgr.Stop(2 * time.Second)
683
684 extToolAdapter := &extToolAdapter{mgr: extMgr}
685 r.MergeExtensionTools(extToolAdapter)
686
687 // Build the swarm supervisor BEFORE the agent so the auto-swarm
688 // tool can reference it during tool-registry construction. State
689 // lives under ZotHome/swarm so per-agent meta/events survive
690 // restarts; the user can hunt orphaned agents down with
691 // `git worktree list` if anything misbehaves.
692 //
693 // swarmMgr is also captured by loadSession / changeCWD closures
694 // further down the function, which is why we keep the variable
695 // in this outer scope rather than scoping it tighter.
696 var swarmMgr *swarm.Swarm
697 swarmMgr = swarm.New(swarm.Config{
698 Root: filepath.Join(ZotHome(), "swarm"),
699 RepoRoot: r.CWD,
700 ResolveCredential: func(ctx context.Context, providerID string) (swarm.Credential, error) {
701 if providerID == "ollama" {
702 return swarm.Credential{Value: "ollama", Method: "apikey"}, nil
703 }
704 credential, method, accountID, err := ResolveCredentialFullContext(ctx, providerID, "")
705 if err != nil {
706 // Providers backed only by a local endpoint do not need a key.
707 // Leave stdin untouched and let the child resolve that endpoint.
708 if !CredentialAvailable(providerID) {
709 return swarm.Credential{}, nil
710 }
711 return swarm.Credential{}, err
712 }
713 return swarm.Credential{Value: credential, Method: method, AccountID: accountID}, nil
714 },
715 })
716 // Pull any previously-spawned agents off disk so the dashboard
717 // shows them as detached and the user can resume / remove them.
718 _, _ = swarmMgr.Reload()
719
720 // onSpawnedSwarm is the OnSpawned callback the swarm_spawn tool
721 // fires after every successful spawn. It hands the agent off to
722 // the running Interactive so the watcher can flush a summary back
723 // into chat when all sub-agents finish. Reads `iv` lazily because
724 // the Interactive is constructed after the agent.
725 onSpawnedSwarm := func(a *swarm.Agent, task string) {
726 if iv != nil {
727 iv.TrackSwarmAgent(a, task)
728 }
729 }
730
731 // Inject the swarm_spawn auto-swarm tool only when /settings ->
732 // auto-swarm is currently enabled. Registering it unconditionally
733 // leaves the model trying to call it (and getting a polite error)
734 // even when the user has switched the feature off. The /settings
735 // toggle live-mutates the running agent's registry separately so
736 // flipping the flag mid-session takes effect on the next turn.
737 injectSwarmSpawn := func(reg core.Registry) core.Registry {
738 if reg == nil {
739 return reg
740 }
741 if !AutoSwarmEnabled() {
742 return reg
743 }
744 reg["swarm_spawn"] = &tools.SwarmSpawnTool{
745 Swarm: swarmMgr,
746 Enabled: AutoSwarmEnabled,
747 DefaultModel: func() string { return r.Model },
748 DefaultProvider: func() string { return r.Provider },
749 OnSpawned: onSpawnedSwarm,
750 }
751 return reg
752 }
753 injectSwarmSpawn(r.ToolRegistry)
754
755 // Confirmation gate: when --no-yolo is on, the agent must ask
756 // the user before every tool call. In interactive mode the TUI
757 // provides the Confirmer; in print/json/rpc modes there's no
758 // way to prompt, so the gate is constructed with a nil inner
759 // which auto-refuses every call with a helpful reason.
760 var confirmGate *core.ConfirmGate
761 if args.NoYolo {
762 confirmGate = core.NewConfirmGate(nil) // set below for interactive
763 }
764
765 // Capture current args in a closure so BuildAgent can re-resolve
766 // after a successful login (picks up the newly stored credential).
767 wireAgentExt := func(a *core.Agent) *core.Agent {
768 if a == nil {
769 return a
770 }
771 a.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
772 // Guards run before confirmation because they may rewrite the
773 // arguments. The user must approve the effective call that will
774 // actually execute, not the model's original arguments.
775 r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
776 if r.Block {
777 return false, r.Reason, nil
778 }
779 effectiveArgs := call.Arguments
780 if len(r.ModifiedArgs) > 0 && json.Valid(r.ModifiedArgs) {
781 effectiveArgs = r.ModifiedArgs
782 }
783 if confirmGate != nil {
784 var content strings.Builder
785 if tool, err := a.Tools.Get(call.Name); err == nil {
786 if previewer, ok := tool.(core.ToolPreviewer); ok {
787 preview, err := previewer.Preview(ctx, effectiveArgs)
788 if err != nil {
789 return false, err.Error(), nil
790 }
791 for _, block := range preview.Content {
792 if text, ok := block.(provider.TextBlock); ok {
793 if content.Len() > 0 {
794 content.WriteString("\n")
795 }
796 content.WriteString(text.Text)
797 }
798 }
799 }
800 }
801 ok, reason, _ := confirmGate.CheckToolCall(core.ToolCallConfirmation{
802 ID: call.ID,
803 Name: call.Name,
804 Summary: core.BuildPreview(effectiveArgs, 120),
805 Content: content.String(),
806 })
807 if !ok {
808 return false, reason, nil
809 }
810 }
811 return true, "", r.ModifiedArgs
812 }
813 a.BeforeTurn = func(step int) (bool, string) {
814 r := extMgr.InterceptTurnStart(ctx, step)
815 return !r.Block, r.Reason
816 }
817 a.BeforeAssistantMessage = func(text string) (bool, string, string) {
818 r := extMgr.InterceptAssistantMessage(ctx, text)
819 if r.Block {
820 return false, r.Reason, ""
821 }
822 return true, "", r.ReplaceText
823 }
824 a.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
825 return a
826 }
827
828 buildAgent := func() (*core.Agent, string, string, error) {
829 resolved, err := Resolve(args, true)
830 if err != nil {
831 return nil, "", "", err
832 }
833 resolved.UseSandbox(sharedSandbox)
834 resolved.MergeExtensionTools(extToolAdapter)
835 injectSwarmSpawn(resolved.ToolRegistry)
836 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
837 }
838
839 // Rebuild agent with an explicit provider/model override.
840 buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
841 next := args
842 if providerOverride != "" {
843 next.Provider = providerOverride
844 }
845 if modelOverride != "" {
846 next.Model = modelOverride
847 }
848 resolved, err := Resolve(next, true)
849 if err != nil {
850 return nil, "", "", err
851 }
852 resolved.UseSandbox(sharedSandbox)
853 resolved.MergeExtensionTools(extToolAdapter)
854 injectSwarmSpawn(resolved.ToolRegistry)
855 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
856 }
857
858 // Rebuild agent for the rescue picker after a recoverable failure.
859 // Unlike buildAgentFor, this drops launch-time --api-key and
860 // --base-url overrides because those are typically the cause of the
861 // rescue (a bad key, a typo'd base URL, or a corporate gateway that
862 // only the originally-picked provider needed). Re-resolving without
863 // them lets the rescue retry use env vars / auth.json / provider
864 // defaults the way zot would have without the overrides.
865 buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
866 next := args
867 next.APIKey = ""
868 next.BaseURL = ""
869 if providerOverride != "" {
870 next.Provider = providerOverride
871 }
872 if modelOverride != "" {
873 next.Model = modelOverride
874 }
875 resolved, err := Resolve(next, true)
876 if err != nil {
877 return nil, "", "", err
878 }
879 resolved.UseSandbox(sharedSandbox)
880 resolved.MergeExtensionTools(extToolAdapter)
881 injectSwarmSpawn(resolved.ToolRegistry)
882 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
883 }
884
885 var ag *core.Agent
886 if r.HasCredential() {
887 ag = wireAgentExt(r.NewAgent())
888 }
889
890 // /reload-ext callback: after the manager has respawned every
891 // extension, re-resolve the tool registry (built-ins + freshly-
892 // registered extension tools) and swap it onto the current
893 // agent in-place. The current agent may have been replaced by a
894 // /model swap since spawn, so re-read the live `ag` on each
895 // invocation.
896 extMgr.SetOnReload(func() {
897 current := liveInteractiveAgent(iv, ag)
898 if current == nil {
899 return
900 }
901 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
902 })
903
904 // Fire session_start once we know the manager's running.
905 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
906
907 var sess *core.Session
908 var sessBaselineMsgs int // messages already on disk when current session opened
909 // persistMu guards sess + sessBaselineMsgs against concurrent access
910 // from the agent loop's per-message persistence hook (runs on the
911 // agent goroutine) and the TUI's session swap / flush callbacks
912 // (run on the TUI goroutine). Without this, a /sessions swap that
913 // races with a finishing turn could double-write or lose messages.
914 var persistMu sync.Mutex
915 if !args.NoSess && ag != nil {
916 sess, _ = openOrCreateSession(args, r, ag, version)
917 if ag != nil {
918 sessBaselineMsgs = len(ag.Messages())
919 }
920 }
921 defer func() {
922 persistMu.Lock()
923 defer persistMu.Unlock()
924 if sess != nil {
925 sess.Close()
926 }
927 }()
928
929 // persistMessage is the per-message hook bound to the agent. It
930 // appends each new transcript message to the live session as soon
931 // as it lands, so a kill / closed terminal / OS crash costs at
932 // most the in-flight turn instead of the whole session. The
933 // baseline counter advances in lock-step so the exit-time flush
934 // doesn't double-write rows already on disk.
935 persistMessage := func(m provider.Message) {
936 persistMu.Lock()
937 defer persistMu.Unlock()
938 if sess == nil {
939 return
940 }
941 if err := sess.AppendMessage(m); err == nil {
942 sessBaselineMsgs++
943 }
944 }
945 persistUsage := func(cum provider.Usage) {
946 persistMu.Lock()
947 defer persistMu.Unlock()
948 if sess == nil {
949 return
950 }
951 _ = sess.AppendUsage(cum, cum)
952 }
953 persistCompaction := func(messages []provider.Message) {
954 persistMu.Lock()
955 defer persistMu.Unlock()
956 if sess == nil {
957 return
958 }
959 if err := sess.AppendCompaction(messages); err == nil {
960 sessBaselineMsgs = len(messages)
961 }
962 }
963 wireAgentPersist := func(a *core.Agent) *core.Agent {
964 if a == nil {
965 return a
966 }
967 a.OnMessageAppended = persistMessage
968 a.OnUsage = persistUsage
969 a.OnTranscriptCompacted = persistCompaction
970 return a
971 }
972 wireAgentPersist(ag)
973
974 // Re-wrap the build closures so any agent constructed by the TUI
975 // (login, /model swap to a different provider) also gets the
976 // persistence hooks. Without this, switching provider would
977 // silently revert to the old in-memory-only behaviour.
978 baseBuildAgent := buildAgent
979 buildAgent = func() (*core.Agent, string, string, error) {
980 a, p, m, err := baseBuildAgent()
981 return wireAgentPersist(a), p, m, err
982 }
983 baseBuildAgentFor := buildAgentFor
984 buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
985 a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
986 return wireAgentPersist(a), p, m, err
987 }
988 baseBuildAgentForRescue := buildAgentForRescue
989 buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
990 a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
991 return wireAgentPersist(a), p, m, err
992 }
993
994 // loadSession replaces the current session with the one at path and
995 // hands its messages to the agent. Used by the /sessions picker.
996 loadSession := func(path string) error {
997 currentAg := liveInteractiveAgent(iv, ag)
998 if currentAg == nil {
999 return fmt.Errorf("no agent running; log in first")
1000 }
1001 newSess, msgs, err := core.OpenSession(path)
1002 if err != nil {
1003 return err
1004 }
1005 fullMsgCount := len(msgs)
1006 msgs = trimMessagesForResume(msgs, 100)
1007 persistMu.Lock()
1008 // Flush any unsaved messages to the old session before swapping.
1009 // Per-message persistence keeps sessBaselineMsgs current, so
1010 // this is a defensive no-op in the common case; it still
1011 // matters for the rare race where a turn just finished and
1012 // hadn't fired its hook yet.
1013 if sess != nil {
1014 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1015 _ = sess.Close()
1016 }
1017 sess = newSess
1018 currentAg.SetMessages(msgs)
1019 if cum, last, uerr := core.SessionUsageDetail(path); uerr == nil {
1020 currentAg.SeedCost(cum)
1021 currentAg.SeedLastTurnUsage(last)
1022 }
1023 // The live agent only receives a compact resume window, but
1024 // the session file remains intact. Keep the persistence
1025 // baseline at the original on-disk message count so future
1026 // turns append after the full session instead of duplicating
1027 // the hydrated tail.
1028 sessBaselineMsgs = fullMsgCount
1029 persistMu.Unlock()
1030 // Re-scope the swarm dashboard to the new session so /swarm
1031 // only shows agents this session spawned. swarmMgr may be nil
1032 // here if we haven't reached the construction site yet (it
1033 // shouldn't be, since the interactive loop is what triggers
1034 // loadSession, but the nil check is cheap insurance).
1035 if swarmMgr != nil && newSess != nil {
1036 swarmMgr.SetActiveSession(newSess.ID)
1037 }
1038 return nil
1039 }
1040
1041 // changeCWD switches the running session to a new working directory.
1042 // Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
1043 // /cd slash command (which itself is only fired by the workspaces
1044 // extension's panel-key Enter handler today; the user can type /cd
1045 // directly but it's not in autocomplete / help / the README).
1046 //
1047 // Steps, in order:
1048 // 1. resolve + validate the new path (~ expansion, abs/rel)
1049 // 2. close the current session, flushing pending messages
1050 // 3. mutate captured args.CWD + r.CWD so future buildAgent
1051 // calls bind to the new cwd
1052 // 4. re-root the shared sandbox («·«) so /jail follows the
1053 // session into the new cwd instead of widening or silently
1054 // dropping
1055 // 5. rebuild the agent via buildAgent() so tools, AGENTS.md
1056 // addendum, system prompt, sessions dir all bind correctly
1057 // 6. open a fresh session in the new cwd's bucket
1058 // 7. push the new state into the running Interactive
1059 // 8. re-scope the swarm dashboard to the freshly-opened session
1060 //
1061 // The /jail state is preserved verbatim: if the sandbox was locked
1062 // to the old cwd, it stays locked, just re-pointed at the new one.
1063 changeCWD := func(path string) error {
1064 if path == "" {
1065 return fmt.Errorf("empty path")
1066 }
1067 // ~ expansion.
1068 if path == "~" || strings.HasPrefix(path, "~/") {
1069 home, herr := os.UserHomeDir()
1070 if herr != nil || home == "" {
1071 return fmt.Errorf("cannot expand ~: %v", herr)
1072 }
1073 if path == "~" {
1074 path = home
1075 } else {
1076 path = filepath.Join(home, path[2:])
1077 }
1078 }
1079 if !filepath.IsAbs(path) {
1080 path = filepath.Join(args.CWD, path)
1081 }
1082 absPath, err := filepath.Abs(path)
1083 if err != nil {
1084 return err
1085 }
1086 info, err := os.Stat(absPath)
1087 if err != nil {
1088 return err
1089 }
1090 if !info.IsDir() {
1091 return fmt.Errorf("not a directory: %s", absPath)
1092 }
1093
1094 currentAg := ag
1095 if currentAg == nil {
1096 return fmt.Errorf("no agent running; log in first")
1097 }
1098
1099 // Close the current session before we drop the reference.
1100 // Per-message persistence keeps it current already; this is
1101 // a defensive flush + final fsync via Close.
1102 persistMu.Lock()
1103 if sess != nil {
1104 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1105 _ = sess.Close()
1106 sess = nil
1107 }
1108 sessBaselineMsgs = 0
1109 persistMu.Unlock()
1110
1111 // Mutate captured state so subsequent agent rebuilds and
1112 // session opens see the new cwd.
1113 wasJailed := sharedSandbox != nil && sharedSandbox.Locked()
1114 args.CWD = absPath
1115 r.CWD = absPath
1116 if args.PermissionSet != nil {
1117 expanded := args.PermissionSet.Expand(absPath, args.AgentDataDir)
1118 args.PermissionSet = &expanded
1119 }
1120 if sharedSandbox != nil {
1121 sharedSandbox.Root = absPath
1122 if wasJailed {
1123 sharedSandbox.Lock()
1124 } else {
1125 sharedSandbox.Unlock()
1126 }
1127 }
1128
1129 // Rebuild the agent so tools / AGENTS.md / system prompt
1130 // re-bind to the new cwd. buildAgent() reads from args + r.
1131 newAg, newProvider, newModel, berr := buildAgent()
1132 if berr != nil {
1133 return fmt.Errorf("rebuild agent: %v", berr)
1134 }
1135 ag = newAg
1136
1137 // Fresh session in the new cwd's bucket. We bypass
1138 // openOrCreateSession's --continue / --resume branches
1139 // because /cd's semantics are "start fresh here", matching
1140 // what relaunching `zot --cwd <path>` would do today.
1141 if !args.NoSess {
1142 newRoot := agentSessionsRoot(ZotHome(), args)
1143 core.PruneEmptySessions(newRoot, absPath)
1144 newSess, serr := core.NewSession(newRoot, absPath, newProvider, newModel, version)
1145 if serr != nil {
1146 return fmt.Errorf("open session in %s: %v", absPath, serr)
1147 }
1148 persistMu.Lock()
1149 sess = newSess
1150 sessBaselineMsgs = 0
1151 persistMu.Unlock()
1152 }
1153
1154 // Push the new state into the running Interactive.
1155 if iv != nil {
1156 startupPaths := instructionContextPaths(loadAgentsContext(absPath, ZotHome()))
1157 iv.ApplyChangedCWDWithStartupContext(newAg, newProvider, newModel, absPath, startupPaths)
1158 }
1159
1160 // Re-scope the swarm dashboard to the new session.
1161 if swarmMgr != nil && sess != nil {
1162 swarmMgr.SetActiveSession(sess.ID)
1163 }
1164 return nil
1165 }
1166
1167 term := tui.NewProcTerm()
1168
1169 // Kick off the async update check so the banner can appear when the
1170 // http response eventually arrives (usually <1s on cached DNS). Map
1171 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
1172 updateCh := make(chan modes.UpdateInfo, 1)
1173 go func() {
1174 defer close(updateCh)
1175 src := <-CheckForUpdateAsync(ZotHome(), version)
1176 updateCh <- modes.UpdateInfo{
1177 Current: src.Current,
1178 Latest: src.Latest,
1179 Available: src.Available,
1180 URL: src.URL,
1181 }
1182 }()
1183
1184 // Changelog: when the running version differs from the last
1185 // version whose release notes the user dismissed, fetch the
1186 // release body from GitHub and have the TUI show it once. On
1187 // first-ever launch (no prior LastChangelogShown), seed the
1188 // stored version silently — don't dump release notes at someone
1189 // who just installed.
1190 changelogCh := make(chan modes.ChangelogPayload, 1)
1191 go func() {
1192 defer close(changelogCh)
1193 cfg, _ := LoadConfig()
1194 if cfg.LastChangelogShown == "" {
1195 SeedChangelogVersion(version)
1196 return
1197 }
1198 if !ShouldShowChangelog(version, cfg) {
1199 return
1200 }
1201 info := <-FetchChangelogAsync(version)
1202 if info.Body == "" {
1203 return
1204 }
1205 // For dev builds (0.0.0), skip if the latest release was
1206 // already shown (stored by the dismiss callback).
1207 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
1208 return
1209 }
1210 changelogCh <- modes.ChangelogPayload{
1211 Version: info.Version,
1212 Body: info.Body,
1213 URL: info.URL,
1214 }
1215 }()
1216
1217 initialCfg, _ := LoadConfig()
1218 quickModelShortcuts := make([]modes.QuickModelShortcut, len(initialCfg.QuickModelShortcuts))
1219 for idx, s := range initialCfg.QuickModelShortcuts {
1220 quickModelShortcuts[idx] = modes.QuickModelShortcut{Provider: s.Provider, Model: s.Model}
1221 }
1222 theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
1223 if themeErr != nil {
1224 fmt.Fprintln(os.Stderr, "theme load:", themeErr)
1225 if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
1226 initialCfg.Theme = ""
1227 _ = SaveConfig(initialCfg)
1228 }
1229 }
1230
1231 // swarmMgr was constructed and reloaded earlier (before the agent
1232 // build, so the auto-swarm tool could capture it). Here we just
1233 // scope the dashboard to the active host session so /swarm only
1234 // shows agents this session spawned (and any pre-upgrade unscoped
1235 // agents — see SnapshotAll docs). Updated again whenever the
1236 // user swaps sessions via loadSession below.
1237 if sess != nil {
1238 swarmMgr.SetActiveSession(sess.ID)
1239 }
1240 // Best-effort shutdown on interactive exit: stop all running
1241 // agents so they don't outlive their parent zot.
1242 defer swarmMgr.StopAll()
1243
1244 var startupSkills []*skills.Skill
1245 if r.SkillTool != nil {
1246 startupSkills = r.SkillTool.Skills()
1247 }
1248
1249 iv = modes.NewInteractive(modes.InteractiveConfig{
1250 Terminal: term,
1251 Theme: theme,
1252 InlineImagesEnabled: initialCfg.InlineImagesEnabled,
1253 AutoSwarmEnabled: initialCfg.AutoSwarmEnabled,
1254 AutoCompactThreshold: initialCfg.AutoCompactThreshold,
1255 JailByDefault: initialCfg.JailByDefault,
1256 QuickModelShortcuts: quickModelShortcuts,
1257 RecursiveFileSuggest: initialCfg.RecursiveFileSuggest,
1258 RespectGitignore: initialCfg.RespectGitignore,
1259 CompactMode: initialCfg.CompactMode,
1260 TUIInputStyle: initialCfg.TUIInputStyle,
1261 TUIStatusPosition: initialCfg.TUIStatusPosition,
1262 TUIWorkingPosition: initialCfg.TUIWorkingPosition,
1263 ThemeName: initialCfg.Theme,
1264 FlatTools: initialCfg.FlatToolRender(),
1265 CompactUser: initialCfg.CompactUserInput(),
1266 ExtensionThemes: extMgr.ThemeOptions,
1267 AutoSwarmSystemAddendum: AutoSwarmSystemAddendum,
1268 SettingsStore: configSettingsStore{},
1269 Model: r.Model,
1270 Provider: r.Provider,
1271 AuthMethod: r.AuthMethod,
1272 BaseURL: r.BaseURL,
1273 Reasoning: r.Reasoning,
1274 SystemPrompt: r.SystemPrompt,
1275 Tools: r.ToolRegistry,
1276 MaxSteps: r.MaxSteps,
1277 CWD: r.CWD,
1278 StartupAgentName: args.AgentName,
1279 StartupContextPaths: instructionContextPaths(r.ContextFiles),
1280 StartupExtensionNames: startupExtensionNames(extMgr.All()),
1281 StartupExtensionErrors: startupExtensionErrors,
1282 StartupSkillNames: startupSkillNames(startupSkills),
1283 ShowInstructionsAtStartup: initialCfg.ShowInstructionsAtStartup,
1284 ZotHome: ZotHome(),
1285 SessionsRoot: agentSessionsRoot(ZotHome(), args),
1286 Version: version,
1287 UpdateInfoChan: updateCh,
1288 Sandbox: sharedSandbox,
1289 Agent: ag,
1290 InitialInput: args.Prompt,
1291 StartupPre: args.StartupPre,
1292 OnStartupPreDone: func() {
1293 // entry.pre often installs skills/extensions; rediscover them
1294 // before the user starts a model turn.
1295 current := liveInteractiveAgent(iv, ag)
1296 if extMgr != nil {
1297 _ = extMgr.Reload(context.Background(), 2*time.Second)
1298 }
1299 if current != nil {
1300 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
1301 }
1302 },
1303 AuthManager: mgr,
1304 LlamaCPPConfig: ResolveLlamaCPPConfig,
1305 RefreshLlamaCPPModels: RefreshLlamaCPPModels,
1306 BuildAgent: buildAgent,
1307 SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
1308 BuildAgentFor: buildAgentFor,
1309 BuildAgentForRescue: buildAgentForRescue,
1310 LoggedInProviders: func() []string {
1311 var out []string
1312 seen := map[string]bool{}
1313 for _, p := range knownProviders {
1314 if CredentialAvailable(p) && !seen[p] {
1315 out = append(out, p)
1316 seen[p] = true
1317 }
1318 }
1319 // Include custom providers that have credentials stored.
1320 for p := range provider.CustomProviders() {
1321 if CredentialAvailable(p) && !seen[p] {
1322 out = append(out, p)
1323 seen[p] = true
1324 }
1325 }
1326 // Ollama models are always available (no auth needed).
1327 if !seen["ollama"] {
1328 out = append(out, "ollama")
1329 }
1330 return out
1331 },
1332 LoadSession: loadSession,
1333 ChangeCWD: changeCWD,
1334 CurrentSessionPath: func() string {
1335 if sess == nil {
1336 return ""
1337 }
1338 return sess.Path
1339 },
1340 FlushSession: func() {
1341 // Append any not-yet-persisted agent messages to the
1342 // current session file, then advance the baseline so
1343 // the final WriteNewTranscript at exit doesn't write
1344 // duplicates. Per-message persistence keeps the on-
1345 // disk file current already, so this is mostly a
1346 // defensive flush — still needed for /session export
1347 // to guarantee the exported bytes include the very
1348 // last in-flight turn.
1349 currentAg := iv.Agent()
1350 if currentAg == nil {
1351 return
1352 }
1353 persistMu.Lock()
1354 defer persistMu.Unlock()
1355 if sess == nil {
1356 return
1357 }
1358 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1359 sessBaselineMsgs = len(currentAg.Messages())
1360 },
1361 Extensions: extMgr,
1362 Swarm: swarmMgr,
1363 ChangelogChan: changelogCh,
1364 OnChangelogDismiss: func() {
1365 // For dev builds (0.0.0) store the actual release version
1366 // so the same changelog doesn't show again next launch.
1367 // For real builds, store the binary version.
1368 v := version
1369 if v == "0.0.0" {
1370 if iv != nil && iv.ChangelogVersion() != "" {
1371 v = iv.ChangelogVersion()
1372 }
1373 }
1374 _ = MarkChangelogShown(v)
1375 },
1376 SkillSnapshot: func() []*skills.Skill {
1377 if args.NoSkill {
1378 // --no-skill: nothing for the picker to show.
1379 return nil
1380 }
1381 // Re-discover so the picker reflects edits made during
1382 // the session. Cheap; SKILL.md files are small. Filter
1383 // out built-in skills — they're hidden from user-facing
1384 // surfaces because they're implementation detail; the
1385 // model still sees them through the system-prompt
1386 // manifest and the skill tool.
1387 userHome, _ := os.UserHomeDir()
1388 list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
1389 return skills.VisibleSkills(list)
1390 },
1391 NoYolo: args.NoYolo,
1392 ConfirmGate: confirmGate,
1393 PersistModel: func(providerName, model string) {
1394 // Update config.json so next launch uses the same pick.
1395 cfg, _ := LoadConfig()
1396 cfg.Provider = providerName
1397 cfg.Model = model
1398 _ = SaveConfig(cfg)
1399 // Update the active session's meta so resume picks this up.
1400 if sess != nil {
1401 _ = sess.UpdateModel(providerName, model)
1402 }
1403 },
1404 })
1405
1406 // Bind the interactive TUI as the Confirmer. We deferred this
1407 // until now because the gate is constructed before the TUI
1408 // (the BeforeToolExecute closure captures it). SetConfirmer
1409 // is mutex-guarded on the gate so this is safe.
1410 if confirmGate != nil {
1411 confirmGate.SetConfirmer(&confirmationEventConfirmer{
1412 inner: iv,
1413 emit: extMgr.EmitEvent,
1414 })
1415 }
1416
1417 // Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1418 // (closed terminal window, system shutdown, kill) used to lose
1419 // the entire in-memory transcript because the deferred post-Run
1420 // flush below never ran. Per-message persistence above covers
1421 // most of it; this handler writes any in-flight remainder and
1422 // then exits the process so we don't double-paint over a
1423 // broken terminal that the TUI's restore deferreds can no
1424 // longer fix from a signal context.
1425 //
1426 // SIGINT is intentionally NOT handled here — the TUI consumes
1427 // Ctrl+C as a regular key event for cancel/clear semantics, and
1428 // installing a SIGINT notifier here would swallow it.
1429 sigCh := make(chan os.Signal, 1)
1430 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1431 defer signal.Stop(sigCh)
1432 go func() {
1433 _, ok := <-sigCh
1434 if !ok {
1435 return
1436 }
1437 if finalAg := iv.Agent(); finalAg != nil {
1438 persistMu.Lock()
1439 if sess != nil {
1440 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1441 sessBaselineMsgs = len(finalAg.Messages())
1442 _ = sess.Close()
1443 sess = nil
1444 }
1445 persistMu.Unlock()
1446 }
1447 // Exit cleanly. Re-raising the signal would skip os.Exit's
1448 // at-exit hooks; explicit exit is fine because we've already
1449 // flushed the only at-risk state (the session file).
1450 os.Exit(0)
1451 }()
1452
1453 runErr := iv.Run(ctx)
1454
1455 // Flush final transcript to session (only if we had / ended up with an agent).
1456 if finalAg := iv.Agent(); finalAg != nil {
1457 persistMu.Lock()
1458 if sess != nil {
1459 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1460 sessBaselineMsgs = len(finalAg.Messages())
1461 }
1462 persistMu.Unlock()
1463 }
1464 return runErr
1465}
1466
1467func agentSessionsRoot(root string, args Args) string {
1468 if args.AgentName == "" {
1469 return root
1470 }
1471 return filepath.Join(root, "sessions", "agents", safeAgentName(args.AgentName))
1472}
1473
1474// openOrCreateSession returns a session for the run. sess may be nil
1475// with a nil error if session persistence is disabled.
1476func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1477 if args.NoSess {
1478 return nil, nil
1479 }
1480 // Sweep meta-only files left over from older zot versions (and from
1481 // any session that crashed before its first AppendMessage). Cheap;
1482 // reads the first few bytes of each file in the cwd's session dir.
1483 sessionsRoot := agentSessionsRoot(ZotHome(), args)
1484 core.PruneEmptySessions(sessionsRoot, args.CWD)
1485 var (
1486 s *core.Session
1487 msgs []provider.Message
1488 err error
1489 )
1490 switch {
1491 case args.Session != "":
1492 s, msgs, err = core.OpenSession(args.Session)
1493 // The swarm-agent child passes a fixed --session path that
1494 // may not exist yet on first Spawn. Treat ENOENT as "create
1495 // a fresh session AT THIS PATH" so the conversation actually
1496 // gets persisted; without this fallback the swarm child runs
1497 // with sess==nil and every Resume re-starts with no memory
1498 // of the prior turns. Other openers (--continue / --resume /
1499 // the picker) never see ENOENT here because they only choose
1500 // paths that already exist on disk.
1501 if err != nil && errors.Is(err, os.ErrNotExist) {
1502 s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1503 msgs = nil
1504 }
1505 case args.Continue:
1506 latest := core.LatestSession(sessionsRoot, args.CWD)
1507 if latest != "" {
1508 s, msgs, err = core.OpenSession(latest)
1509 }
1510 case args.Resume:
1511 picked, perr := pickSession(sessionsRoot, args.CWD)
1512 if perr != nil {
1513 return nil, perr
1514 }
1515 if picked != "" {
1516 s, msgs, err = core.OpenSession(picked)
1517 }
1518 }
1519 if err != nil {
1520 return nil, err
1521 }
1522 if s != nil {
1523 ag.SetMessages(msgs)
1524 if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1525 ag.SeedCost(cum)
1526 ag.SeedLastTurnUsage(last)
1527 }
1528 return s, nil
1529 }
1530 return core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
1531}
1532
1533func pickSession(root, cwd string) (string, error) {
1534 files := core.ListSessions(root, cwd)
1535 if len(files) == 0 {
1536 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1537 return "", nil
1538 }
1539 for i, f := range files {
1540 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
1541 }
1542 fmt.Fprint(os.Stderr, "pick #: ")
1543 rd := bufio.NewReader(os.Stdin)
1544 line, _ := rd.ReadString('\n')
1545 line = strings.TrimSpace(line)
1546 var n int
1547 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1548 return "", fmt.Errorf("invalid selection")
1549 }
1550 return files[n-1], nil
1551}
1552
1553// WriteNewTranscript appends only messages after index `from` from the
1554// agent's transcript to the session. Used by callers that don't hold
1555// the persistMu (non-interactive print/json modes which run a single
1556// turn under their own goroutine).
1557func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1558 writeNewTranscriptLocked(ag, sess, from)
1559}
1560
1561// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1562// suffix marks that interactive callers must hold persistMu when
1563// invoking it so concurrent appends from the agent loop don't race
1564// with this catch-up flush.
1565func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1566 if sess == nil || ag == nil {
1567 return
1568 }
1569 msgs := ag.Messages()
1570 for i := from; i < len(msgs); i++ {
1571 _ = sess.AppendMessage(msgs[i])
1572 }
1573 cum := ag.Cost()
1574 _ = sess.AppendUsage(cum, cum)
1575}
1576
1577func argsForStdin(rawArgs []string, mode os.FileMode) []string {
1578 if mode&os.ModeCharDevice != 0 {
1579 return rawArgs
1580 }
1581 return append([]string{"--print"}, rawArgs...)
1582}
1583
1584func combinePromptInput(stdin, positional string) string {
1585 parts := make([]string, 0, 2)
1586 if stdin = strings.TrimSpace(stdin); stdin != "" {
1587 parts = append(parts, stdin)
1588 }
1589 if positional = strings.TrimSpace(positional); positional != "" {
1590 parts = append(parts, positional)
1591 }
1592 return strings.Join(parts, "\n")
1593}
1594
1595func readAllStdin() (string, error) {
1596 fi, err := os.Stdin.Stat()
1597 if err != nil {
1598 return "", err
1599 }
1600 if (fi.Mode() & os.ModeCharDevice) != 0 {
1601 return "", nil
1602 }
1603 b, err := io.ReadAll(os.Stdin)
1604 return string(b), err
1605}
1606
1607func printModels() {
1608 models := provider.Active()
1609
1610 // Compute column widths from actual data so wide providers (e.g.
1611 // xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1612 // `name` column off-screen. Floors mirror the historical layout so
1613 // short catalogs look the same as before.
1614 provW, idW, srcW := len("provider"), len("model id"), len("source")
1615 for _, m := range models {
1616 if w := len(m.Provider); w > provW {
1617 provW = w
1618 }
1619 if w := len(m.ID); w > idW {
1620 idW = w
1621 }
1622 source := m.Source
1623 if source == "" {
1624 source = "catalog"
1625 }
1626 if m.Speculative {
1627 source = "speculative"
1628 }
1629 if w := len(source); w > srcW {
1630 srcW = w
1631 }
1632 }
1633
1634 header := fmt.Sprintf("%-*s %-*s %8s %8s %s %-*s %s",
1635 provW, "provider",
1636 idW, "model id",
1637 "context", "max-out", "reasoning",
1638 srcW, "source",
1639 "name")
1640 fmt.Println(header)
1641
1642 for _, m := range models {
1643 reason := " "
1644 if m.Reasoning {
1645 reason = "✓"
1646 }
1647 source := m.Source
1648 if source == "" {
1649 source = "catalog"
1650 }
1651 if m.Speculative {
1652 source = "speculative"
1653 }
1654 fmt.Printf("%-*s %-*s %8d %8d %s %-*s %s\n",
1655 provW, m.Provider,
1656 idW, m.ID,
1657 m.ContextWindow, m.MaxOutput,
1658 reason,
1659 srcW, source,
1660 m.DisplayName)
1661 }
1662}