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