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