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 sessBaselineMsgs = len(msgs)
516 return nil
517 }
518
519 term := tui.NewProcTerm()
520
521 // Kick off the async update check so the banner can appear when the
522 // http response eventually arrives (usually <1s on cached DNS). Map
523 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
524 updateCh := make(chan modes.UpdateInfo, 1)
525 go func() {
526 defer close(updateCh)
527 src := <-CheckForUpdateAsync(ZotHome(), version)
528 updateCh <- modes.UpdateInfo{
529 Current: src.Current,
530 Latest: src.Latest,
531 Available: src.Available,
532 URL: src.URL,
533 }
534 }()
535
536 // Changelog: when the running version differs from the last
537 // version whose release notes the user dismissed, fetch the
538 // release body from GitHub and have the TUI show it once. On
539 // first-ever launch (no prior LastChangelogShown), seed the
540 // stored version silently — don't dump release notes at someone
541 // who just installed.
542 changelogCh := make(chan modes.ChangelogPayload, 1)
543 go func() {
544 defer close(changelogCh)
545 cfg, _ := LoadConfig()
546 if cfg.LastChangelogShown == "" {
547 SeedChangelogVersion(version)
548 return
549 }
550 if !ShouldShowChangelog(version, cfg) {
551 return
552 }
553 info := <-FetchChangelogAsync(version)
554 if info.Body == "" {
555 return
556 }
557 // For dev builds (0.0.0), skip if the latest release was
558 // already shown (stored by the dismiss callback).
559 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
560 return
561 }
562 changelogCh <- modes.ChangelogPayload{
563 Version: info.Version,
564 Body: info.Body,
565 URL: info.URL,
566 }
567 }()
568
569 iv = modes.NewInteractive(modes.InteractiveConfig{
570 Terminal: term,
571 Theme: tui.Dark,
572 Model: r.Model,
573 Provider: r.Provider,
574 AuthMethod: r.AuthMethod,
575 BaseURL: r.BaseURL,
576 Reasoning: r.Reasoning,
577 SystemPrompt: r.SystemPrompt,
578 Tools: r.ToolRegistry,
579 MaxSteps: r.MaxSteps,
580 CWD: r.CWD,
581 ZotHome: ZotHome(),
582 Version: version,
583 UpdateInfoChan: updateCh,
584 Sandbox: sharedSandbox,
585 Agent: ag,
586 InitialInput: args.Prompt,
587 AuthManager: mgr,
588 BuildAgent: buildAgent,
589 BuildAgentFor: buildAgentFor,
590 LoadSession: loadSession,
591 CurrentSessionPath: func() string {
592 if sess == nil {
593 return ""
594 }
595 return sess.Path
596 },
597 FlushSession: func() {
598 // Append any not-yet-persisted agent messages to the
599 // current session file, then advance the baseline so
600 // the final WriteNewTranscript at exit doesn't write
601 // duplicates. Called by /session export so the
602 // exported bytes include everything the user has
603 // said in the running TUI, not just whatever got
604 // flushed at startup.
605 if sess == nil {
606 return
607 }
608 currentAg := iv.Agent()
609 if currentAg == nil {
610 return
611 }
612 WriteNewTranscript(currentAg, sess, sessBaselineMsgs)
613 sessBaselineMsgs = len(currentAg.Messages())
614 },
615 Extensions: extMgr,
616 ChangelogChan: changelogCh,
617 OnChangelogDismiss: func() {
618 // For dev builds (0.0.0) store the actual release version
619 // so the same changelog doesn't show again next launch.
620 // For real builds, store the binary version.
621 v := version
622 if v == "0.0.0" {
623 if iv != nil && iv.ChangelogVersion() != "" {
624 v = iv.ChangelogVersion()
625 }
626 }
627 _ = MarkChangelogShown(v)
628 },
629 SkillSnapshot: func() []*skills.Skill {
630 if args.NoSkill {
631 // --no-skill: nothing for the picker to show.
632 return nil
633 }
634 // Re-discover so the picker reflects edits made during
635 // the session. Cheap; SKILL.md files are small. Filter
636 // out built-in skills — they're hidden from user-facing
637 // surfaces because they're implementation detail; the
638 // model still sees them through the system-prompt
639 // manifest and the skill tool. User skills only appear
640 // when --with-skills is set; without it the picker shows
641 // nothing but the model still has the built-ins.
642 userHome, _ := os.UserHomeDir()
643 list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
644 return skills.VisibleSkills(list)
645 },
646 NoYolo: args.NoYolo,
647 ConfirmGate: confirmGate,
648 PersistModel: func(providerName, model string) {
649 // Update config.json so next launch uses the same pick.
650 cfg, _ := LoadConfig()
651 cfg.Provider = providerName
652 cfg.Model = model
653 _ = SaveConfig(cfg)
654 // Update the active session's meta so resume picks this up.
655 if sess != nil {
656 _ = sess.UpdateModel(providerName, model)
657 }
658 },
659 })
660
661 // Bind the interactive TUI as the Confirmer. We deferred this
662 // until now because the gate is constructed before the TUI
663 // (the BeforeToolExecute closure captures it). SetConfirmer
664 // is mutex-guarded on the gate so this is safe.
665 if confirmGate != nil {
666 confirmGate.SetConfirmer(iv)
667 }
668
669 runErr := iv.Run(ctx)
670
671 // Flush final transcript to session (only if we had / ended up with an agent).
672 if finalAg := iv.Agent(); finalAg != nil && sess != nil {
673 WriteNewTranscript(finalAg, sess, sessBaselineMsgs)
674 }
675 return runErr
676}
677
678// openOrCreateSession returns a session for the run. sess may be nil
679// with a nil error if session persistence is disabled.
680func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
681 if args.NoSess {
682 return nil, nil
683 }
684 // Sweep meta-only files left over from older zot versions (and from
685 // any session that crashed before its first AppendMessage). Cheap;
686 // reads the first few bytes of each file in the cwd's session dir.
687 core.PruneEmptySessions(ZotHome(), args.CWD)
688 var (
689 s *core.Session
690 msgs []provider.Message
691 err error
692 )
693 switch {
694 case args.Session != "":
695 s, msgs, err = core.OpenSession(args.Session)
696 case args.Continue:
697 latest := core.LatestSession(ZotHome(), args.CWD)
698 if latest != "" {
699 s, msgs, err = core.OpenSession(latest)
700 }
701 case args.Resume:
702 picked, perr := pickSession(args.CWD)
703 if perr != nil {
704 return nil, perr
705 }
706 if picked != "" {
707 s, msgs, err = core.OpenSession(picked)
708 }
709 }
710 if err != nil {
711 return nil, err
712 }
713 if s != nil {
714 ag.SetMessages(msgs)
715 return s, nil
716 }
717 return core.NewSession(ZotHome(), args.CWD, r.Provider, r.Model, version)
718}
719
720func pickSession(cwd string) (string, error) {
721 files := core.ListSessions(ZotHome(), cwd)
722 if len(files) == 0 {
723 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
724 return "", nil
725 }
726 for i, f := range files {
727 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
728 }
729 fmt.Fprint(os.Stderr, "pick #: ")
730 rd := bufio.NewReader(os.Stdin)
731 line, _ := rd.ReadString('\n')
732 line = strings.TrimSpace(line)
733 var n int
734 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
735 return "", fmt.Errorf("invalid selection")
736 }
737 return files[n-1], nil
738}
739
740// WriteNewTranscript appends only messages after index `from` from the
741// agent's transcript to the session.
742func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
743 if sess == nil || ag == nil {
744 return
745 }
746 msgs := ag.Messages()
747 for i := from; i < len(msgs); i++ {
748 _ = sess.AppendMessage(msgs[i])
749 }
750 cum := ag.Cost()
751 _ = sess.AppendUsage(cum, cum)
752}
753
754func readAllStdin() (string, error) {
755 fi, err := os.Stdin.Stat()
756 if err != nil {
757 return "", err
758 }
759 if (fi.Mode() & os.ModeCharDevice) != 0 {
760 return "", nil
761 }
762 b, err := io.ReadAll(os.Stdin)
763 return string(b), err
764}
765
766func printModels() {
767 fmt.Println("provider model id context max-out reasoning source name")
768 for _, m := range provider.Active() {
769 reason := " "
770 if m.Reasoning {
771 reason = "✓"
772 }
773 source := m.Source
774 if source == "" {
775 source = "catalog"
776 }
777 if m.Speculative {
778 source = "speculative"
779 }
780 fmt.Printf("%-10s %-30s %8d %8d %s %-11s %s\n",
781 m.Provider, m.ID, m.ContextWindow, m.MaxOutput, reason, source, m.DisplayName)
782 }
783}