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 // Rebuild agent for the rescue picker after a recoverable failure.
479 // Unlike buildAgentFor, this drops launch-time --api-key and
480 // --base-url overrides because those are typically the cause of the
481 // rescue (a bad key, a typo'd base URL, or a corporate gateway that
482 // only the originally-picked provider needed). Re-resolving without
483 // them lets the rescue retry use env vars / auth.json / provider
484 // defaults the way zot would have without the overrides.
485 buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
486 next := args
487 next.APIKey = ""
488 next.BaseURL = ""
489 if providerOverride != "" {
490 next.Provider = providerOverride
491 }
492 if modelOverride != "" {
493 next.Model = modelOverride
494 }
495 resolved, err := Resolve(next, true)
496 if err != nil {
497 return nil, "", "", err
498 }
499 resolved.UseSandbox(sharedSandbox)
500 resolved.MergeExtensionTools(extToolAdapter)
501 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
502 }
503
504 var ag *core.Agent
505 if r.HasCredential() {
506 ag = wireAgentExt(r.NewAgent())
507 }
508
509 // /reload-ext callback: after the manager has respawned every
510 // extension, re-resolve the tool registry (built-ins + freshly-
511 // registered extension tools) and swap it onto the current
512 // agent in-place. The current agent may have been replaced by a
513 // /model swap since spawn, so re-read the live `ag` on each
514 // invocation.
515 extMgr.SetOnReload(func() {
516 current := ag
517 if current == nil {
518 return
519 }
520 resolved, err := Resolve(args, true)
521 if err != nil {
522 return
523 }
524 resolved.UseSandbox(sharedSandbox)
525 resolved.MergeExtensionTools(extToolAdapter)
526 current.SetTools(resolved.ToolRegistry)
527 })
528
529 // Fire session_start once we know the manager's running.
530 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
531
532 var sess *core.Session
533 var sessBaselineMsgs int // messages already on disk when current session opened
534 // persistMu guards sess + sessBaselineMsgs against concurrent access
535 // from the agent loop's per-message persistence hook (runs on the
536 // agent goroutine) and the TUI's session swap / flush callbacks
537 // (run on the TUI goroutine). Without this, a /sessions swap that
538 // races with a finishing turn could double-write or lose messages.
539 var persistMu sync.Mutex
540 if !args.NoSess && ag != nil {
541 sess, _ = openOrCreateSession(args, r, ag, version)
542 if ag != nil {
543 sessBaselineMsgs = len(ag.Messages())
544 }
545 }
546 defer func() {
547 persistMu.Lock()
548 defer persistMu.Unlock()
549 if sess != nil {
550 sess.Close()
551 }
552 }()
553
554 // persistMessage is the per-message hook bound to the agent. It
555 // appends each new transcript message to the live session as soon
556 // as it lands, so a kill / closed terminal / OS crash costs at
557 // most the in-flight turn instead of the whole session. The
558 // baseline counter advances in lock-step so the exit-time flush
559 // doesn't double-write rows already on disk.
560 persistMessage := func(m provider.Message) {
561 persistMu.Lock()
562 defer persistMu.Unlock()
563 if sess == nil {
564 return
565 }
566 if err := sess.AppendMessage(m); err == nil {
567 sessBaselineMsgs++
568 }
569 }
570 persistUsage := func(cum provider.Usage) {
571 persistMu.Lock()
572 defer persistMu.Unlock()
573 if sess == nil {
574 return
575 }
576 _ = sess.AppendUsage(cum, cum)
577 }
578 wireAgentPersist := func(a *core.Agent) *core.Agent {
579 if a == nil {
580 return a
581 }
582 a.OnMessageAppended = persistMessage
583 a.OnUsage = persistUsage
584 return a
585 }
586 wireAgentPersist(ag)
587
588 // Re-wrap the build closures so any agent constructed by the TUI
589 // (login, /model swap to a different provider) also gets the
590 // persistence hooks. Without this, switching provider would
591 // silently revert to the old in-memory-only behaviour.
592 baseBuildAgent := buildAgent
593 buildAgent = func() (*core.Agent, string, string, error) {
594 a, p, m, err := baseBuildAgent()
595 return wireAgentPersist(a), p, m, err
596 }
597 baseBuildAgentFor := buildAgentFor
598 buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
599 a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
600 return wireAgentPersist(a), p, m, err
601 }
602 baseBuildAgentForRescue := buildAgentForRescue
603 buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
604 a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
605 return wireAgentPersist(a), p, m, err
606 }
607
608 // loadSession replaces the current session with the one at path and
609 // hands its messages to the agent. Used by the /sessions picker.
610 loadSession := func(path string) error {
611 currentAg := ag // captured
612 if currentAg == nil {
613 return fmt.Errorf("no agent running; log in first")
614 }
615 newSess, msgs, err := core.OpenSession(path)
616 if err != nil {
617 return err
618 }
619 fullMsgCount := len(msgs)
620 msgs = trimMessagesForResume(msgs, 100)
621 persistMu.Lock()
622 // Flush any unsaved messages to the old session before swapping.
623 // Per-message persistence keeps sessBaselineMsgs current, so
624 // this is a defensive no-op in the common case; it still
625 // matters for the rare race where a turn just finished and
626 // hadn't fired its hook yet.
627 if sess != nil {
628 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
629 _ = sess.Close()
630 }
631 sess = newSess
632 currentAg.SetMessages(msgs)
633 if usage, uerr := core.SessionUsage(path); uerr == nil {
634 currentAg.SeedCost(usage)
635 }
636 // The live agent only receives a compact resume window, but
637 // the session file remains intact. Keep the persistence
638 // baseline at the original on-disk message count so future
639 // turns append after the full session instead of duplicating
640 // the hydrated tail.
641 sessBaselineMsgs = fullMsgCount
642 persistMu.Unlock()
643 return nil
644 }
645
646 term := tui.NewProcTerm()
647
648 // Kick off the async update check so the banner can appear when the
649 // http response eventually arrives (usually <1s on cached DNS). Map
650 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
651 updateCh := make(chan modes.UpdateInfo, 1)
652 go func() {
653 defer close(updateCh)
654 src := <-CheckForUpdateAsync(ZotHome(), version)
655 updateCh <- modes.UpdateInfo{
656 Current: src.Current,
657 Latest: src.Latest,
658 Available: src.Available,
659 URL: src.URL,
660 }
661 }()
662
663 // Changelog: when the running version differs from the last
664 // version whose release notes the user dismissed, fetch the
665 // release body from GitHub and have the TUI show it once. On
666 // first-ever launch (no prior LastChangelogShown), seed the
667 // stored version silently — don't dump release notes at someone
668 // who just installed.
669 changelogCh := make(chan modes.ChangelogPayload, 1)
670 go func() {
671 defer close(changelogCh)
672 cfg, _ := LoadConfig()
673 if cfg.LastChangelogShown == "" {
674 SeedChangelogVersion(version)
675 return
676 }
677 if !ShouldShowChangelog(version, cfg) {
678 return
679 }
680 info := <-FetchChangelogAsync(version)
681 if info.Body == "" {
682 return
683 }
684 // For dev builds (0.0.0), skip if the latest release was
685 // already shown (stored by the dismiss callback).
686 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
687 return
688 }
689 changelogCh <- modes.ChangelogPayload{
690 Version: info.Version,
691 Body: info.Body,
692 URL: info.URL,
693 }
694 }()
695
696 initialCfg, _ := LoadConfig()
697 iv = modes.NewInteractive(modes.InteractiveConfig{
698 Terminal: term,
699 Theme: tui.DetectThemeFromBackground(80 * time.Millisecond),
700 InlineImagesEnabled: initialCfg.InlineImagesEnabled,
701 SettingsStore: configSettingsStore{},
702 Model: r.Model,
703 Provider: r.Provider,
704 AuthMethod: r.AuthMethod,
705 BaseURL: r.BaseURL,
706 Reasoning: r.Reasoning,
707 SystemPrompt: r.SystemPrompt,
708 Tools: r.ToolRegistry,
709 MaxSteps: r.MaxSteps,
710 CWD: r.CWD,
711 ZotHome: ZotHome(),
712 Version: version,
713 UpdateInfoChan: updateCh,
714 Sandbox: sharedSandbox,
715 Agent: ag,
716 InitialInput: args.Prompt,
717 AuthManager: mgr,
718 BuildAgent: buildAgent,
719 SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
720 BuildAgentFor: buildAgentFor,
721 BuildAgentForRescue: buildAgentForRescue,
722 LoggedInProviders: func() []string {
723 var out []string
724 for _, p := range []string{"anthropic", "openai", "kimi", "google"} {
725 if _, _, err := ResolveCredential(p, ""); err == nil {
726 out = append(out, p)
727 }
728 }
729 // Ollama models are always available (no auth needed).
730 out = append(out, "ollama")
731 return out
732 },
733 LoadSession: loadSession,
734 CurrentSessionPath: func() string {
735 if sess == nil {
736 return ""
737 }
738 return sess.Path
739 },
740 FlushSession: func() {
741 // Append any not-yet-persisted agent messages to the
742 // current session file, then advance the baseline so
743 // the final WriteNewTranscript at exit doesn't write
744 // duplicates. Per-message persistence keeps the on-
745 // disk file current already, so this is mostly a
746 // defensive flush — still needed for /session export
747 // to guarantee the exported bytes include the very
748 // last in-flight turn.
749 currentAg := iv.Agent()
750 if currentAg == nil {
751 return
752 }
753 persistMu.Lock()
754 defer persistMu.Unlock()
755 if sess == nil {
756 return
757 }
758 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
759 sessBaselineMsgs = len(currentAg.Messages())
760 },
761 Extensions: extMgr,
762 ChangelogChan: changelogCh,
763 OnChangelogDismiss: func() {
764 // For dev builds (0.0.0) store the actual release version
765 // so the same changelog doesn't show again next launch.
766 // For real builds, store the binary version.
767 v := version
768 if v == "0.0.0" {
769 if iv != nil && iv.ChangelogVersion() != "" {
770 v = iv.ChangelogVersion()
771 }
772 }
773 _ = MarkChangelogShown(v)
774 },
775 SkillSnapshot: func() []*skills.Skill {
776 if args.NoSkill {
777 // --no-skill: nothing for the picker to show.
778 return nil
779 }
780 // Re-discover so the picker reflects edits made during
781 // the session. Cheap; SKILL.md files are small. Filter
782 // out built-in skills — they're hidden from user-facing
783 // surfaces because they're implementation detail; the
784 // model still sees them through the system-prompt
785 // manifest and the skill tool. User skills only appear
786 // when --with-skills is set; without it the picker shows
787 // nothing but the model still has the built-ins.
788 userHome, _ := os.UserHomeDir()
789 list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
790 return skills.VisibleSkills(list)
791 },
792 NoYolo: args.NoYolo,
793 ConfirmGate: confirmGate,
794 PersistModel: func(providerName, model string) {
795 // Update config.json so next launch uses the same pick.
796 cfg, _ := LoadConfig()
797 cfg.Provider = providerName
798 cfg.Model = model
799 _ = SaveConfig(cfg)
800 // Update the active session's meta so resume picks this up.
801 if sess != nil {
802 _ = sess.UpdateModel(providerName, model)
803 }
804 },
805 })
806
807 // Bind the interactive TUI as the Confirmer. We deferred this
808 // until now because the gate is constructed before the TUI
809 // (the BeforeToolExecute closure captures it). SetConfirmer
810 // is mutex-guarded on the gate so this is safe.
811 if confirmGate != nil {
812 confirmGate.SetConfirmer(iv)
813 }
814
815 // Signal-driven flush: a SIGTERM / SIGHUP to the zot process
816 // (closed terminal window, system shutdown, kill) used to lose
817 // the entire in-memory transcript because the deferred post-Run
818 // flush below never ran. Per-message persistence above covers
819 // most of it; this handler writes any in-flight remainder and
820 // then exits the process so we don't double-paint over a
821 // broken terminal that the TUI's restore deferreds can no
822 // longer fix from a signal context.
823 //
824 // SIGINT is intentionally NOT handled here — the TUI consumes
825 // Ctrl+C as a regular key event for cancel/clear semantics, and
826 // installing a SIGINT notifier here would swallow it.
827 sigCh := make(chan os.Signal, 1)
828 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
829 defer signal.Stop(sigCh)
830 go func() {
831 _, ok := <-sigCh
832 if !ok {
833 return
834 }
835 if finalAg := iv.Agent(); finalAg != nil {
836 persistMu.Lock()
837 if sess != nil {
838 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
839 sessBaselineMsgs = len(finalAg.Messages())
840 _ = sess.Close()
841 sess = nil
842 }
843 persistMu.Unlock()
844 }
845 // Exit cleanly. Re-raising the signal would skip os.Exit's
846 // at-exit hooks; explicit exit is fine because we've already
847 // flushed the only at-risk state (the session file).
848 os.Exit(0)
849 }()
850
851 runErr := iv.Run(ctx)
852
853 // Flush final transcript to session (only if we had / ended up with an agent).
854 if finalAg := iv.Agent(); finalAg != nil {
855 persistMu.Lock()
856 if sess != nil {
857 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
858 sessBaselineMsgs = len(finalAg.Messages())
859 }
860 persistMu.Unlock()
861 }
862 return runErr
863}
864
865// openOrCreateSession returns a session for the run. sess may be nil
866// with a nil error if session persistence is disabled.
867func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
868 if args.NoSess {
869 return nil, nil
870 }
871 // Sweep meta-only files left over from older zot versions (and from
872 // any session that crashed before its first AppendMessage). Cheap;
873 // reads the first few bytes of each file in the cwd's session dir.
874 core.PruneEmptySessions(ZotHome(), args.CWD)
875 var (
876 s *core.Session
877 msgs []provider.Message
878 err error
879 )
880 switch {
881 case args.Session != "":
882 s, msgs, err = core.OpenSession(args.Session)
883 case args.Continue:
884 latest := core.LatestSession(ZotHome(), args.CWD)
885 if latest != "" {
886 s, msgs, err = core.OpenSession(latest)
887 }
888 case args.Resume:
889 picked, perr := pickSession(args.CWD)
890 if perr != nil {
891 return nil, perr
892 }
893 if picked != "" {
894 s, msgs, err = core.OpenSession(picked)
895 }
896 }
897 if err != nil {
898 return nil, err
899 }
900 if s != nil {
901 ag.SetMessages(msgs)
902 if usage, uerr := core.SessionUsage(s.Path); uerr == nil {
903 ag.SeedCost(usage)
904 }
905 return s, nil
906 }
907 return core.NewSession(ZotHome(), args.CWD, r.Provider, r.Model, version)
908}
909
910func pickSession(cwd string) (string, error) {
911 files := core.ListSessions(ZotHome(), cwd)
912 if len(files) == 0 {
913 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
914 return "", nil
915 }
916 for i, f := range files {
917 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
918 }
919 fmt.Fprint(os.Stderr, "pick #: ")
920 rd := bufio.NewReader(os.Stdin)
921 line, _ := rd.ReadString('\n')
922 line = strings.TrimSpace(line)
923 var n int
924 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
925 return "", fmt.Errorf("invalid selection")
926 }
927 return files[n-1], nil
928}
929
930// WriteNewTranscript appends only messages after index `from` from the
931// agent's transcript to the session. Used by callers that don't hold
932// the persistMu (non-interactive print/json modes which run a single
933// turn under their own goroutine).
934func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
935 writeNewTranscriptLocked(ag, sess, from)
936}
937
938// writeNewTranscriptLocked is the same as WriteNewTranscript. The
939// suffix marks that interactive callers must hold persistMu when
940// invoking it so concurrent appends from the agent loop don't race
941// with this catch-up flush.
942func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
943 if sess == nil || ag == nil {
944 return
945 }
946 msgs := ag.Messages()
947 for i := from; i < len(msgs); i++ {
948 _ = sess.AppendMessage(msgs[i])
949 }
950 cum := ag.Cost()
951 _ = sess.AppendUsage(cum, cum)
952}
953
954func readAllStdin() (string, error) {
955 fi, err := os.Stdin.Stat()
956 if err != nil {
957 return "", err
958 }
959 if (fi.Mode() & os.ModeCharDevice) != 0 {
960 return "", nil
961 }
962 b, err := io.ReadAll(os.Stdin)
963 return string(b), err
964}
965
966func printModels() {
967 fmt.Println("provider model id context max-out reasoning source name")
968 for _, m := range provider.Active() {
969 reason := " "
970 if m.Reasoning {
971 reason = "✓"
972 }
973 source := m.Source
974 if source == "" {
975 source = "catalog"
976 }
977 if m.Speculative {
978 source = "speculative"
979 }
980 fmt.Printf("%-10s %-30s %8d %8d %s %-11s %s\n",
981 m.Provider, m.ID, m.ContextWindow, m.MaxOutput, reason, source, m.DisplayName)
982 }
983}