1package agent
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "os/signal"
11 "strings"
12 "sync"
13 "syscall"
14 "time"
15
16 "github.com/patriceckhart/zot/internal/agent/extensions"
17 "github.com/patriceckhart/zot/internal/agent/modes"
18 "github.com/patriceckhart/zot/internal/auth"
19 "github.com/patriceckhart/zot/internal/core"
20 "github.com/patriceckhart/zot/internal/extproto"
21 "github.com/patriceckhart/zot/internal/provider"
22 "github.com/patriceckhart/zot/internal/skills"
23 "github.com/patriceckhart/zot/internal/tui"
24)
25
26// interactiveExtHooks is a tiny adapter that lets the extension
27// manager call back into the Interactive instance built later in
28// runInteractive. The forward-declared *modes.Interactive is filled
29// in immediately after manager construction.
30type interactiveExtHooks struct {
31 ivPtr **modes.Interactive
32}
33
34func (h *interactiveExtHooks) iv() *modes.Interactive {
35 if h == nil || h.ivPtr == nil {
36 return nil
37 }
38 return *h.ivPtr
39}
40
41func (h *interactiveExtHooks) Notify(extName, level, message string) {
42 if iv := h.iv(); iv != nil {
43 iv.Notify(extName, level, message)
44 }
45}
46func (h *interactiveExtHooks) Submit(text string) {
47 if iv := h.iv(); iv != nil {
48 iv.Submit(text)
49 }
50}
51func (h *interactiveExtHooks) Insert(text string) {
52 if iv := h.iv(); iv != nil {
53 iv.Insert(text)
54 }
55}
56func (h *interactiveExtHooks) Display(extName, text string) {
57 if iv := h.iv(); iv != nil {
58 iv.Display(extName, text)
59 }
60}
61func (h *interactiveExtHooks) OpenPanel(extName string, spec extproto.PanelSpec) {
62 if iv := h.iv(); iv != nil {
63 iv.OpenPanel(extName, spec)
64 }
65}
66func (h *interactiveExtHooks) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
67 if iv := h.iv(); iv != nil {
68 iv.UpdatePanel(extName, panelID, title, lines, footer)
69 }
70}
71func (h *interactiveExtHooks) ClosePanel(extName, panelID string) {
72 if iv := h.iv(); iv != nil {
73 iv.ClosePanel(extName, panelID)
74 }
75}
76
77// extToolAdapter bridges *extensions.Manager to the
78// ExtensionToolSource interface declared in build.go (kept narrow to
79// avoid a build->extensions import cycle). One adapter instance per
80// run; used at every Resolve point so re-built agents pick up the
81// same set of extension tools.
82type extToolAdapter struct {
83 mgr *extensions.Manager
84}
85
86func (a *extToolAdapter) Tools() []ExtensionToolInfo {
87 infos := a.mgr.Tools()
88 out := make([]ExtensionToolInfo, len(infos))
89 for i, t := range infos {
90 out[i] = ExtensionToolInfo{
91 Extension: t.Extension,
92 Name: t.Name,
93 Description: t.Description,
94 Schema: t.Schema,
95 }
96 }
97 return out
98}
99
100func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
101 return extensions.NewTool(a.mgr, extensions.ToolInfo{
102 Extension: info.Extension,
103 Name: info.Name,
104 Description: info.Description,
105 Schema: info.Schema,
106 })
107}
108
109// fanoutAgentEvent translates a core.AgentEvent into the wire-format
110// EventFromHost and pushes it through the extension manager. Only
111// the events that have a clear extension-facing meaning are
112// forwarded; internal-only ones (text_delta, tool_progress) are
113// dropped to keep the per-extension stream sane.
114func trimMessagesForResume(msgs []provider.Message, keepTail int) []provider.Message {
115 if keepTail <= 0 || len(msgs) <= keepTail {
116 return provider.RepairOrphanedToolResults(msgs)
117 }
118 var out []provider.Message
119 start := len(msgs) - keepTail
120 // Preserve the synthetic compaction summary when present so an
121 // already-compacted session stays compacted after resume.
122 if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" && start > 1 {
123 out = append(out, msgs[0])
124 }
125 // Avoid hydrating a tail that starts with orphan tool_result rows;
126 // provider APIs require those to be paired with an earlier tool_use.
127 for start < len(msgs) && msgs[start].Role == provider.RoleTool {
128 start++
129 }
130 out = append(out, msgs[start:]...)
131 return provider.RepairOrphanedToolResults(out)
132}
133
134func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
135 if mgr == nil {
136 return
137 }
138 switch e := ev.(type) {
139 case core.EvTurnStart:
140 mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
141 case core.EvToolCall:
142 mgr.EmitEvent(extproto.EventFromHost{
143 Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
144 })
145 case core.EvAssistantMessage:
146 // Concat the visible text portions of the message; binary
147 // blocks (tool_use, etc.) are skipped because subscribers
148 // usually want a string they can grep / display.
149 var text string
150 for _, c := range e.Message.Content {
151 if tb, ok := c.(provider.TextBlock); ok {
152 text += tb.Text
153 }
154 }
155 mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
156 case core.EvTurnEnd:
157 ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
158 if e.Err != nil {
159 ev.Error = e.Err.Error()
160 }
161 mgr.EmitEvent(ev)
162 }
163}
164
165// Run is the top-level entrypoint for the zot binary.
166func Run(rawArgs []string, version string) error {
167 // Subcommand router: `zot bot ...` is handled separately so the
168 // generic flag parser doesn't reject "bot" as a positional arg.
169 if handled, err := runBotCommand(rawArgs, version); handled {
170 return err
171 }
172 if handled, err := runExtCommand(rawArgs); handled {
173 return err
174 }
175 // `zot rpc` is shorthand for `zot --rpc` so third-party apps can
176 // spawn the binary with a clean argv. Strip the leading 'rpc'
177 // token and let the rest flow through the normal arg parser.
178 if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
179 rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
180 }
181
182 args, err := ParseArgs(rawArgs)
183 if err != nil {
184 PrintHelp(version)
185 return err
186 }
187 if args.Help {
188 PrintHelp(version)
189 return nil
190 }
191 if args.Version {
192 fmt.Println("zot", version)
193 return nil
194 }
195 // Model catalog: load any cached discovery data before we inspect
196 // the model list (list-models, print/json, interactive).
197 LoadCachedModels()
198 LoadUserModels()
199
200 if args.ListModels {
201 printModels()
202 return nil
203 }
204
205 ctx := context.Background()
206
207 // Kick an async refresh of the live model catalog. The first run of
208 // zot hits the network; subsequent runs within CacheTTL do nothing.
209 RefreshModelsAsync()
210
211 switch args.Mode {
212 case ModePrint:
213 return runPrintMode(ctx, args, version)
214 case ModeJSON:
215 return runJSONMode(ctx, args, version)
216 case ModeRPC:
217 return runRPCMode(ctx, args, version)
218 default:
219 return runInteractive(ctx, args, version)
220 }
221}
222
223// ---- print / json modes: require credentials, run single-shot ----
224
225// nonInteractiveExtHooks is the HostHooks impl used by print / json
226// modes. They have no TUI, so notify / display go to stderr and
227// submit / insert are no-ops (the extension can't steer a
228// single-shot run once it's in flight anyway).
229type nonInteractiveExtHooks struct{}
230
231func (nonInteractiveExtHooks) Notify(ext, level, message string) {
232 fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
233}
234func (nonInteractiveExtHooks) Submit(string) {}
235func (nonInteractiveExtHooks) Insert(string) {}
236func (nonInteractiveExtHooks) Display(string, string) {}
237func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec) {}
238func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
239func (nonInteractiveExtHooks) ClosePanel(string, string) {}
240
241// setupNonInteractiveExtensions loads --ext paths and (unless
242// --no-ext) runs discovery. Returns the manager so the caller can
243// wire tools into the resolved registry, and a cleanup closure to
244// defer. Mirrors the interactive-mode setup minus the TUI hooks.
245func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
246 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
247 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
248 fmt.Fprintln(os.Stderr, "extension load:", e)
249 }
250 if !args.NoExt {
251 for _, e := range extMgr.Discover(ctx) {
252 fmt.Fprintln(os.Stderr, "extension load:", e)
253 }
254 }
255 extMgr.WaitForReady(3 * time.Second)
256 r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
257 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
258 return extMgr, func() { extMgr.Stop(2 * time.Second) }
259}
260
261// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
262// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
263// interactive path wires up, so extensions get their normal
264// event-intercept surface in print / json / rpc flows too.
265func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
266 if ag == nil || extMgr == nil {
267 return
268 }
269 ag.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
270 res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
271 if res.Block {
272 return false, res.Reason, nil
273 }
274 return true, "", res.ModifiedArgs
275 }
276 ag.BeforeTurn = func(step int) (bool, string) {
277 res := extMgr.InterceptTurnStart(ctx, step)
278 return !res.Block, res.Reason
279 }
280 ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
281 res := extMgr.InterceptAssistantMessage(ctx, text)
282 if res.Block {
283 return false, res.Reason, ""
284 }
285 return true, "", res.ReplaceText
286 }
287 ag.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
288}
289
290func runPrintMode(ctx context.Context, args Args, version string) error {
291 if args.NoYolo {
292 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
293 }
294 r, err := Resolve(args, true)
295 if err != nil {
296 return err
297 }
298 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
299 defer stopExt()
300
301 ag := r.NewAgent()
302 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
303 sess, _ := openOrCreateSession(args, r, ag, version)
304 defer sess.Close()
305
306 prompt := args.Prompt
307 if prompt == "" {
308 piped, _ := readAllStdin()
309 prompt = strings.TrimSpace(piped)
310 }
311 if prompt == "" {
312 return fmt.Errorf("print mode requires a prompt (arg or stdin)")
313 }
314
315 start := len(ag.Messages())
316 err = modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
317 WriteNewTranscript(ag, sess, start)
318 return err
319}
320
321func runJSONMode(ctx context.Context, args Args, version string) error {
322 if args.NoYolo {
323 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
324 }
325 r, err := Resolve(args, true)
326 if err != nil {
327 return err
328 }
329 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
330 defer stopExt()
331
332 ag := r.NewAgent()
333 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
334 sess, _ := openOrCreateSession(args, r, ag, version)
335 defer sess.Close()
336
337 prompt := args.Prompt
338 if prompt == "" {
339 piped, _ := readAllStdin()
340 prompt = strings.TrimSpace(piped)
341 }
342 if prompt == "" {
343 return fmt.Errorf("json mode requires a prompt (arg or stdin)")
344 }
345
346 start := len(ag.Messages())
347 err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
348 WriteNewTranscript(ag, sess, start)
349 return err
350}
351
352// ---- interactive mode: opens the TUI even without credentials ----
353
354func runInteractive(ctx context.Context, args Args, version string) error {
355 // Resolve WITHOUT requiring credentials.
356 r, err := Resolve(args, false)
357 if err != nil {
358 return err
359 }
360
361 authStore := AuthStoreFor()
362 mgr := auth.NewManager(authStore)
363 defer mgr.Close()
364
365 // Keep the sandbox pointer stable across agent rebuilds (login / model
366 // switch). The Interactive UI toggles the lock via this pointer, and
367 // rebuilt tool instances must share the same one so the lock sticks.
368 sharedSandbox := r.Sandbox
369
370 // Build the extension manager BEFORE the agent so we can fold
371 // extension-defined tools into the registry. Forward-declare iv so
372 // the host hooks adapter can dereference it after construction.
373 var iv *modes.Interactive
374 extHooks := &interactiveExtHooks{ivPtr: &iv}
375 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
376 // --ext paths first so they win against installed extensions of
377 // the same name (loadOne's first-write-wins semantics).
378 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
379 fmt.Fprintln(os.Stderr, "extension load:", e)
380 }
381 // --no-ext skips the global + project-local discovery scan;
382 // explicit --ext paths above are still honoured so you can run
383 // "only this extension" with --no-ext --ext ./x.
384 if !args.NoExt {
385 for _, e := range extMgr.Discover(ctx) {
386 fmt.Fprintln(os.Stderr, "extension load:", e)
387 }
388 }
389 // Wait briefly for extensions to flush their initial register_tool
390 // frames before we build the agent's tool registry. Half a second
391 // is plenty for any extension that's actually well-behaved; ones
392 // that don't send a ready frame eat the full grace and proceed.
393 // 3s is the per-extension grace period for the ready frame.
394 // Native binaries are instant; runtimes like `npx tsx` take ~1.5s
395 // from cold cache. The wait is tight only for extensions that
396 // haven't sent ready by then; ones that signalled earlier release
397 // the wait immediately.
398 extMgr.WaitForReady(3 * time.Second)
399 defer extMgr.Stop(2 * time.Second)
400
401 extToolAdapter := &extToolAdapter{mgr: extMgr}
402 r.MergeExtensionTools(extToolAdapter)
403
404 // Confirmation gate: when --no-yolo is on, the agent must ask
405 // the user before every tool call. In interactive mode the TUI
406 // provides the Confirmer; in print/json/rpc modes there's no
407 // way to prompt, so the gate is constructed with a nil inner
408 // which auto-refuses every call with a helpful reason.
409 var confirmGate *core.ConfirmGate
410 if args.NoYolo {
411 confirmGate = core.NewConfirmGate(nil) // set below for interactive
412 }
413
414 // Capture current args in a closure so BuildAgent can re-resolve
415 // after a successful login (picks up the newly stored credential).
416 wireAgentExt := func(a *core.Agent) *core.Agent {
417 if a == nil {
418 return a
419 }
420 a.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
421 // Confirm gate runs FIRST: if the user refused, we don't
422 // waste extension-intercept time or let guards see the call.
423 if confirmGate != nil {
424 ok, reason, _ := confirmGate.Check(call.Name, core.BuildPreview(call.Arguments, 120))
425 if !ok {
426 return false, reason, nil
427 }
428 }
429 r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
430 if r.Block {
431 return false, r.Reason, nil
432 }
433 return true, "", r.ModifiedArgs
434 }
435 a.BeforeTurn = func(step int) (bool, string) {
436 r := extMgr.InterceptTurnStart(ctx, step)
437 return !r.Block, r.Reason
438 }
439 a.BeforeAssistantMessage = func(text string) (bool, string, string) {
440 r := extMgr.InterceptAssistantMessage(ctx, text)
441 if r.Block {
442 return false, r.Reason, ""
443 }
444 return true, "", r.ReplaceText
445 }
446 a.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
447 return a
448 }
449
450 buildAgent := func() (*core.Agent, string, string, error) {
451 resolved, err := Resolve(args, true)
452 if err != nil {
453 return nil, "", "", err
454 }
455 resolved.UseSandbox(sharedSandbox)
456 resolved.MergeExtensionTools(extToolAdapter)
457 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
458 }
459
460 // Rebuild agent with an explicit provider/model override.
461 buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
462 next := args
463 if providerOverride != "" {
464 next.Provider = providerOverride
465 }
466 if modelOverride != "" {
467 next.Model = modelOverride
468 }
469 resolved, err := Resolve(next, true)
470 if err != nil {
471 return nil, "", "", err
472 }
473 resolved.UseSandbox(sharedSandbox)
474 resolved.MergeExtensionTools(extToolAdapter)
475 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
476 }
477
478 var ag *core.Agent
479 if r.HasCredential() {
480 ag = wireAgentExt(r.NewAgent())
481 }
482
483 // /reload-ext callback: after the manager has respawned every
484 // extension, re-resolve the tool registry (built-ins + freshly-
485 // registered extension tools) and swap it onto the current
486 // agent in-place. The current agent may have been replaced by a
487 // /model swap since spawn, so re-read the live `ag` on each
488 // invocation.
489 extMgr.SetOnReload(func() {
490 current := ag
491 if current == nil {
492 return
493 }
494 resolved, err := Resolve(args, true)
495 if err != nil {
496 return
497 }
498 resolved.UseSandbox(sharedSandbox)
499 resolved.MergeExtensionTools(extToolAdapter)
500 current.SetTools(resolved.ToolRegistry)
501 })
502
503 // Fire session_start once we know the manager's running.
504 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
505
506 var sess *core.Session
507 var sessBaselineMsgs int // messages already on disk when current session opened
508 // persistMu guards sess + sessBaselineMsgs against concurrent access
509 // from the agent loop's per-message persistence hook (runs on the
510 // agent goroutine) and the TUI's session swap / flush callbacks
511 // (run on the TUI goroutine). Without this, a /sessions swap that
512 // races with a finishing turn could double-write or lose messages.
513 var persistMu sync.Mutex
514 if !args.NoSess && ag != nil {
515 sess, _ = openOrCreateSession(args, r, ag, version)
516 if ag != nil {
517 sessBaselineMsgs = len(ag.Messages())
518 }
519 }
520 defer func() {
521 persistMu.Lock()
522 defer persistMu.Unlock()
523 if sess != nil {
524 sess.Close()
525 }
526 }()
527
528 // persistMessage is the per-message hook bound to the agent. It
529 // appends each new transcript message to the live session as soon
530 // as it lands, so a kill / closed terminal / OS crash costs at
531 // most the in-flight turn instead of the whole session. The
532 // baseline counter advances in lock-step so the exit-time flush
533 // doesn't double-write rows already on disk.
534 persistMessage := func(m provider.Message) {
535 persistMu.Lock()
536 defer persistMu.Unlock()
537 if sess == nil {
538 return
539 }
540 if err := sess.AppendMessage(m); err == nil {
541 sessBaselineMsgs++
542 }
543 }
544 persistUsage := func(cum provider.Usage) {
545 persistMu.Lock()
546 defer persistMu.Unlock()
547 if sess == nil {
548 return
549 }
550 _ = sess.AppendUsage(cum, cum)
551 }
552 wireAgentPersist := func(a *core.Agent) *core.Agent {
553 if a == nil {
554 return a
555 }
556 a.OnMessageAppended = persistMessage
557 a.OnUsage = persistUsage
558 return a
559 }
560 wireAgentPersist(ag)
561
562 // Re-wrap the build closures so any agent constructed by the TUI
563 // (login, /model swap to a different provider) also gets the
564 // persistence hooks. Without this, switching provider would
565 // silently revert to the old in-memory-only behaviour.
566 baseBuildAgent := buildAgent
567 buildAgent = func() (*core.Agent, string, string, error) {
568 a, p, m, err := baseBuildAgent()
569 return wireAgentPersist(a), p, m, err
570 }
571 baseBuildAgentFor := buildAgentFor
572 buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
573 a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
574 return wireAgentPersist(a), p, m, err
575 }
576
577 // loadSession replaces the current session with the one at path and
578 // hands its messages to the agent. Used by the /sessions picker.
579 loadSession := func(path string) error {
580 currentAg := ag // captured
581 if currentAg == nil {
582 return fmt.Errorf("no agent running; log in first")
583 }
584 newSess, msgs, err := core.OpenSession(path)
585 if err != nil {
586 return err
587 }
588 fullMsgCount := len(msgs)
589 msgs = trimMessagesForResume(msgs, 100)
590 persistMu.Lock()
591 // Flush any unsaved messages to the old session before swapping.
592 // Per-message persistence keeps sessBaselineMsgs current, so
593 // this is a defensive no-op in the common case; it still
594 // matters for the rare race where a turn just finished and
595 // hadn't fired its hook yet.
596 if sess != nil {
597 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
598 _ = sess.Close()
599 }
600 sess = newSess
601 currentAg.SetMessages(msgs)
602 if usage, uerr := core.SessionUsage(path); uerr == nil {
603 currentAg.SeedCost(usage)
604 }
605 // The live agent only receives a compact resume window, but
606 // the session file remains intact. Keep the persistence
607 // baseline at the original on-disk message count so future
608 // turns append after the full session instead of duplicating
609 // the hydrated tail.
610 sessBaselineMsgs = fullMsgCount
611 persistMu.Unlock()
612 return nil
613 }
614
615 term := tui.NewProcTerm()
616
617 // Kick off the async update check so the banner can appear when the
618 // http response eventually arrives (usually <1s on cached DNS). Map
619 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
620 updateCh := make(chan modes.UpdateInfo, 1)
621 go func() {
622 defer close(updateCh)
623 src := <-CheckForUpdateAsync(ZotHome(), version)
624 updateCh <- modes.UpdateInfo{
625 Current: src.Current,
626 Latest: src.Latest,
627 Available: src.Available,
628 URL: src.URL,
629 }
630 }()
631
632 // Changelog: when the running version differs from the last
633 // version whose release notes the user dismissed, fetch the
634 // release body from GitHub and have the TUI show it once. On
635 // first-ever launch (no prior LastChangelogShown), seed the
636 // stored version silently — don't dump release notes at someone
637 // who just installed.
638 changelogCh := make(chan modes.ChangelogPayload, 1)
639 go func() {
640 defer close(changelogCh)
641 cfg, _ := LoadConfig()
642 if cfg.LastChangelogShown == "" {
643 SeedChangelogVersion(version)
644 return
645 }
646 if !ShouldShowChangelog(version, cfg) {
647 return
648 }
649 info := <-FetchChangelogAsync(version)
650 if info.Body == "" {
651 return
652 }
653 // For dev builds (0.0.0), skip if the latest release was
654 // already shown (stored by the dismiss callback).
655 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
656 return
657 }
658 changelogCh <- modes.ChangelogPayload{
659 Version: info.Version,
660 Body: info.Body,
661 URL: info.URL,
662 }
663 }()
664
665 initialCfg, _ := LoadConfig()
666 iv = modes.NewInteractive(modes.InteractiveConfig{
667 Terminal: term,
668 Theme: tui.DetectThemeFromBackground(80 * time.Millisecond),
669 InlineImagesEnabled: initialCfg.InlineImagesEnabled,
670 SettingsStore: configSettingsStore{},
671 Model: r.Model,
672 Provider: r.Provider,
673 AuthMethod: r.AuthMethod,
674 BaseURL: r.BaseURL,
675 Reasoning: r.Reasoning,
676 SystemPrompt: r.SystemPrompt,
677 Tools: r.ToolRegistry,
678 MaxSteps: r.MaxSteps,
679 CWD: r.CWD,
680 ZotHome: ZotHome(),
681 Version: version,
682 UpdateInfoChan: updateCh,
683 Sandbox: sharedSandbox,
684 Agent: ag,
685 InitialInput: args.Prompt,
686 AuthManager: mgr,
687 BuildAgent: buildAgent,
688 SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
689 BuildAgentFor: buildAgentFor,
690 LoggedInProviders: func() []string {
691 var out []string
692 for _, p := range []string{"anthropic", "openai", "kimi"} {
693 if _, _, err := ResolveCredential(p, ""); err == nil {
694 out = append(out, p)
695 }
696 }
697 // Ollama models are always available (no auth needed).
698 out = append(out, "ollama")
699 return out
700 },
701 LoadSession: loadSession,
702 CurrentSessionPath: func() string {
703 if sess == nil {
704 return ""
705 }
706 return sess.Path
707 },
708 FlushSession: func() {
709 // Append any not-yet-persisted agent messages to the
710 // current session file, then advance the baseline so
711 // the final WriteNewTranscript at exit doesn't write
712 // duplicates. Per-message persistence keeps the on-
713 // disk file current already, so this is mostly a
714 // defensive flush — still needed for /session export
715 // to guarantee the exported bytes include the very
716 // last in-flight turn.
717 currentAg := iv.Agent()
718 if currentAg == nil {
719 return
720 }
721 persistMu.Lock()
722 defer persistMu.Unlock()
723 if sess == nil {
724 return
725 }
726 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
727 sessBaselineMsgs = len(currentAg.Messages())
728 },
729 Extensions: extMgr,
730 ChangelogChan: changelogCh,
731 OnChangelogDismiss: func() {
732 // For dev builds (0.0.0) store the actual release version
733 // so the same changelog doesn't show again next launch.
734 // For real builds, store the binary version.
735 v := version
736 if v == "0.0.0" {
737 if iv != nil && iv.ChangelogVersion() != "" {
738 v = iv.ChangelogVersion()
739 }
740 }
741 _ = MarkChangelogShown(v)
742 },
743 SkillSnapshot: func() []*skills.Skill {
744 if args.NoSkill {
745 // --no-skill: nothing for the picker to show.
746 return nil
747 }
748 // Re-discover so the picker reflects edits made during
749 // the session. Cheap; SKILL.md files are small. Filter
750 // out built-in skills — they're hidden from user-facing
751 // surfaces because they're implementation detail; the
752 // model still sees them through the system-prompt
753 // manifest and the skill tool. User skills only appear
754 // when --with-skills is set; without it the picker shows
755 // nothing but the model still has the built-ins.
756 userHome, _ := os.UserHomeDir()
757 list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
758 return skills.VisibleSkills(list)
759 },
760 NoYolo: args.NoYolo,
761 ConfirmGate: confirmGate,
762 PersistModel: func(providerName, model string) {
763 // Update config.json so next launch uses the same pick.
764 cfg, _ := LoadConfig()
765 cfg.Provider = providerName
766 cfg.Model = model
767 _ = SaveConfig(cfg)
768 // Update the active session's meta so resume picks this up.
769 if sess != nil {
770 _ = sess.UpdateModel(providerName, model)
771 }
772 },
773 })
774
775 // Bind the interactive TUI as the Confirmer. We deferred this
776 // until now because the gate is constructed before the TUI
777 // (the BeforeToolExecute closure captures it). SetConfirmer
778 // is mutex-guarded on the gate so this is safe.
779 if confirmGate != nil {
780 confirmGate.SetConfirmer(iv)
781 }
782
783 // Signal-driven flush: a SIGTERM / SIGHUP to the zot process
784 // (closed terminal window, system shutdown, kill) used to lose
785 // the entire in-memory transcript because the deferred post-Run
786 // flush below never ran. Per-message persistence above covers
787 // most of it; this handler writes any in-flight remainder and
788 // then exits the process so we don't double-paint over a
789 // broken terminal that the TUI's restore deferreds can no
790 // longer fix from a signal context.
791 //
792 // SIGINT is intentionally NOT handled here — the TUI consumes
793 // Ctrl+C as a regular key event for cancel/clear semantics, and
794 // installing a SIGINT notifier here would swallow it.
795 sigCh := make(chan os.Signal, 1)
796 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
797 defer signal.Stop(sigCh)
798 go func() {
799 _, ok := <-sigCh
800 if !ok {
801 return
802 }
803 if finalAg := iv.Agent(); finalAg != nil {
804 persistMu.Lock()
805 if sess != nil {
806 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
807 sessBaselineMsgs = len(finalAg.Messages())
808 _ = sess.Close()
809 sess = nil
810 }
811 persistMu.Unlock()
812 }
813 // Exit cleanly. Re-raising the signal would skip os.Exit's
814 // at-exit hooks; explicit exit is fine because we've already
815 // flushed the only at-risk state (the session file).
816 os.Exit(0)
817 }()
818
819 runErr := iv.Run(ctx)
820
821 // Flush final transcript to session (only if we had / ended up with an agent).
822 if finalAg := iv.Agent(); finalAg != nil {
823 persistMu.Lock()
824 if sess != nil {
825 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
826 sessBaselineMsgs = len(finalAg.Messages())
827 }
828 persistMu.Unlock()
829 }
830 return runErr
831}
832
833// openOrCreateSession returns a session for the run. sess may be nil
834// with a nil error if session persistence is disabled.
835func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
836 if args.NoSess {
837 return nil, nil
838 }
839 // Sweep meta-only files left over from older zot versions (and from
840 // any session that crashed before its first AppendMessage). Cheap;
841 // reads the first few bytes of each file in the cwd's session dir.
842 core.PruneEmptySessions(ZotHome(), args.CWD)
843 var (
844 s *core.Session
845 msgs []provider.Message
846 err error
847 )
848 switch {
849 case args.Session != "":
850 s, msgs, err = core.OpenSession(args.Session)
851 case args.Continue:
852 latest := core.LatestSession(ZotHome(), args.CWD)
853 if latest != "" {
854 s, msgs, err = core.OpenSession(latest)
855 }
856 case args.Resume:
857 picked, perr := pickSession(args.CWD)
858 if perr != nil {
859 return nil, perr
860 }
861 if picked != "" {
862 s, msgs, err = core.OpenSession(picked)
863 }
864 }
865 if err != nil {
866 return nil, err
867 }
868 if s != nil {
869 ag.SetMessages(msgs)
870 if usage, uerr := core.SessionUsage(s.Path); uerr == nil {
871 ag.SeedCost(usage)
872 }
873 return s, nil
874 }
875 return core.NewSession(ZotHome(), args.CWD, r.Provider, r.Model, version)
876}
877
878func pickSession(cwd string) (string, error) {
879 files := core.ListSessions(ZotHome(), cwd)
880 if len(files) == 0 {
881 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
882 return "", nil
883 }
884 for i, f := range files {
885 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
886 }
887 fmt.Fprint(os.Stderr, "pick #: ")
888 rd := bufio.NewReader(os.Stdin)
889 line, _ := rd.ReadString('\n')
890 line = strings.TrimSpace(line)
891 var n int
892 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
893 return "", fmt.Errorf("invalid selection")
894 }
895 return files[n-1], nil
896}
897
898// WriteNewTranscript appends only messages after index `from` from the
899// agent's transcript to the session. Used by callers that don't hold
900// the persistMu (non-interactive print/json modes which run a single
901// turn under their own goroutine).
902func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
903 writeNewTranscriptLocked(ag, sess, from)
904}
905
906// writeNewTranscriptLocked is the same as WriteNewTranscript. The
907// suffix marks that interactive callers must hold persistMu when
908// invoking it so concurrent appends from the agent loop don't race
909// with this catch-up flush.
910func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
911 if sess == nil || ag == nil {
912 return
913 }
914 msgs := ag.Messages()
915 for i := from; i < len(msgs); i++ {
916 _ = sess.AppendMessage(msgs[i])
917 }
918 cum := ag.Cost()
919 _ = sess.AppendUsage(cum, cum)
920}
921
922func readAllStdin() (string, error) {
923 fi, err := os.Stdin.Stat()
924 if err != nil {
925 return "", err
926 }
927 if (fi.Mode() & os.ModeCharDevice) != 0 {
928 return "", nil
929 }
930 b, err := io.ReadAll(os.Stdin)
931 return string(b), err
932}
933
934func printModels() {
935 fmt.Println("provider model id context max-out reasoning source name")
936 for _, m := range provider.Active() {
937 reason := " "
938 if m.Reasoning {
939 reason = "✓"
940 }
941 source := m.Source
942 if source == "" {
943 source = "catalog"
944 }
945 if m.Speculative {
946 source = "speculative"
947 }
948 fmt.Printf("%-10s %-30s %8d %8d %s %-11s %s\n",
949 m.Provider, m.ID, m.ContextWindow, m.MaxOutput, reason, source, m.DisplayName)
950 }
951}