1package agent
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/signal"
12 "path/filepath"
13 "strings"
14 "sync"
15 "syscall"
16 "time"
17
18 "github.com/patriceckhart/zot/packages/agent/extensions"
19 "github.com/patriceckhart/zot/packages/agent/extproto"
20 "github.com/patriceckhart/zot/packages/agent/modes"
21 "github.com/patriceckhart/zot/packages/agent/skills"
22 "github.com/patriceckhart/zot/packages/agent/swarm"
23 "github.com/patriceckhart/zot/packages/agent/tools"
24 "github.com/patriceckhart/zot/packages/core"
25 "github.com/patriceckhart/zot/packages/provider"
26 "github.com/patriceckhart/zot/packages/provider/auth"
27 "github.com/patriceckhart/zot/packages/tui"
28)
29
30// interactiveExtHooks is a tiny adapter that lets the extension
31// manager call back into the Interactive instance built later in
32// runInteractive. The forward-declared *modes.Interactive is filled
33// in immediately after manager construction.
34type interactiveExtHooks struct {
35 ivPtr **modes.Interactive
36}
37
38func (h *interactiveExtHooks) iv() *modes.Interactive {
39 if h == nil || h.ivPtr == nil {
40 return nil
41 }
42 return *h.ivPtr
43}
44
45func (h *interactiveExtHooks) Notify(extName, level, message string) {
46 if iv := h.iv(); iv != nil {
47 iv.Notify(extName, level, message)
48 }
49}
50func (h *interactiveExtHooks) Submit(text string) {
51 if iv := h.iv(); iv != nil {
52 iv.Submit(text)
53 }
54}
55func (h *interactiveExtHooks) SubmitSlash(text string) {
56 if iv := h.iv(); iv != nil {
57 iv.SubmitSlash(text)
58 }
59}
60func (h *interactiveExtHooks) Insert(text string) {
61 if iv := h.iv(); iv != nil {
62 iv.Insert(text)
63 }
64}
65func (h *interactiveExtHooks) Display(extName, text string) {
66 if iv := h.iv(); iv != nil {
67 iv.Display(extName, text)
68 }
69}
70func (h *interactiveExtHooks) ClearNotes(extName string) {
71 if iv := h.iv(); iv != nil {
72 iv.ClearNotes(extName)
73 }
74}
75func (h *interactiveExtHooks) OpenPanel(extName string, spec extproto.PanelSpec) {
76 if iv := h.iv(); iv != nil {
77 iv.OpenPanel(extName, spec)
78 }
79}
80func (h *interactiveExtHooks) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
81 if iv := h.iv(); iv != nil {
82 iv.UpdatePanel(extName, panelID, title, lines, footer)
83 }
84}
85func (h *interactiveExtHooks) ClosePanel(extName, panelID string) {
86 if iv := h.iv(); iv != nil {
87 iv.ClosePanel(extName, panelID)
88 }
89}
90
91// extToolAdapter bridges *extensions.Manager to the
92// ExtensionToolSource interface declared in build.go (kept narrow to
93// avoid a build->extensions import cycle). One adapter instance per
94// run; used at every Resolve point so re-built agents pick up the
95// same set of extension tools.
96type extToolAdapter struct {
97 mgr *extensions.Manager
98}
99
100func (a *extToolAdapter) Tools() []ExtensionToolInfo {
101 infos := a.mgr.Tools()
102 out := make([]ExtensionToolInfo, len(infos))
103 for i, t := range infos {
104 out[i] = ExtensionToolInfo{
105 Extension: t.Extension,
106 Name: t.Name,
107 Description: t.Description,
108 Schema: t.Schema,
109 }
110 }
111 return out
112}
113
114func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
115 return extensions.NewTool(a.mgr, extensions.ToolInfo{
116 Extension: info.Extension,
117 Name: info.Name,
118 Description: info.Description,
119 Schema: info.Schema,
120 })
121}
122
123// fanoutAgentEvent translates a core.AgentEvent into the wire-format
124// EventFromHost and pushes it through the extension manager. Only
125// the events that have a clear extension-facing meaning are
126// forwarded; internal-only ones (text_delta, tool_progress) are
127// dropped to keep the per-extension stream sane.
128func trimMessagesForResume(msgs []provider.Message, keepTail int) []provider.Message {
129 if keepTail <= 0 || len(msgs) <= keepTail {
130 return provider.RepairOrphanedToolResults(msgs)
131 }
132 var out []provider.Message
133 start := len(msgs) - keepTail
134 // Preserve the synthetic compaction summary when present so an
135 // already-compacted session stays compacted after resume.
136 if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" && start > 1 {
137 out = append(out, msgs[0])
138 }
139 // Avoid hydrating a tail that starts with orphan tool_result rows;
140 // provider APIs require those to be paired with an earlier tool_use.
141 for start < len(msgs) && msgs[start].Role == provider.RoleTool {
142 start++
143 }
144 out = append(out, msgs[start:]...)
145 return provider.RepairOrphanedToolResults(out)
146}
147
148func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
149 if mgr == nil {
150 return
151 }
152 switch e := ev.(type) {
153 case core.EvTurnStart:
154 mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
155 case core.EvToolCall:
156 mgr.EmitEvent(extproto.EventFromHost{
157 Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
158 })
159 case core.EvAssistantMessage:
160 // Concat the visible text portions of the message; binary
161 // blocks (tool_use, etc.) are skipped because subscribers
162 // usually want a string they can grep / display.
163 var text string
164 for _, c := range e.Message.Content {
165 if tb, ok := c.(provider.TextBlock); ok {
166 text += tb.Text
167 }
168 }
169 mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
170 case core.EvTurnEnd:
171 ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
172 if e.Err != nil {
173 ev.Error = e.Err.Error()
174 }
175 mgr.EmitEvent(ev)
176 }
177}
178
179// Run is the top-level entrypoint for the zot binary.
180func Run(rawArgs []string, version string) error {
181 // Subcommand router: `zot bot ...` is handled separately so the
182 // generic flag parser doesn't reject "bot" as a positional arg.
183 if handled, err := runBotCommand(rawArgs, version); handled {
184 return err
185 }
186 if handled, err := runExtCommand(rawArgs); handled {
187 return err
188 }
189 if handled, err := runUpdateCommand(rawArgs, version); handled {
190 return err
191 }
192 // `zot rpc` is shorthand for `zot --rpc` so third-party apps can
193 // spawn the binary with a clean argv. Strip the leading 'rpc'
194 // token and let the rest flow through the normal arg parser.
195 if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
196 rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
197 }
198
199 args, err := ParseArgs(rawArgs)
200 if err != nil {
201 PrintHelp(version)
202 return err
203 }
204 if args.Help {
205 PrintHelp(version)
206 return nil
207 }
208 if args.Version {
209 fmt.Println("zot", version)
210 return nil
211 }
212 // Model catalog: load any cached discovery data before we inspect
213 // the model list (list-models, print/json, interactive).
214 LoadCachedModels()
215 LoadUserModels()
216
217 // Repair config.json so a stale (provider, model) pair from an
218 // interrupted /model switch can't strand the user with an
219 // "unknown model" error on the first turn. Runs before any UI
220 // renders so the status bar shows the post-repair pair, not the
221 // broken one. Silent on success.
222 ValidateAndRepairConfig()
223
224 if args.ListModels {
225 printModels()
226 return nil
227 }
228
229 ctx := context.Background()
230
231 // Kick an async refresh of the live model catalog. The first run of
232 // zot hits the network; subsequent runs within CacheTTL do nothing.
233 RefreshModelsAsync()
234
235 switch args.Mode {
236 case ModePrint:
237 return runPrintMode(ctx, args, version)
238 case ModeJSON:
239 return runJSONMode(ctx, args, version)
240 case ModeRPC:
241 return runRPCMode(ctx, args, version)
242 case ModeSwarmAgent:
243 return runSwarmAgentMode(ctx, args, version)
244 default:
245 return runInteractive(ctx, args, version)
246 }
247}
248
249// ---- print / json modes: require credentials, run single-shot ----
250
251// nonInteractiveExtHooks is the HostHooks impl used by print / json
252// modes. They have no TUI, so notify / display go to stderr and
253// submit / insert are no-ops (the extension can't steer a
254// single-shot run once it's in flight anyway).
255type nonInteractiveExtHooks struct{}
256
257func (nonInteractiveExtHooks) Notify(ext, level, message string) {
258 fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
259}
260func (nonInteractiveExtHooks) Submit(string) {}
261func (nonInteractiveExtHooks) SubmitSlash(string) {}
262func (nonInteractiveExtHooks) Insert(string) {}
263func (nonInteractiveExtHooks) Display(string, string) {}
264func (nonInteractiveExtHooks) ClearNotes(string) {}
265func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec) {}
266func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
267func (nonInteractiveExtHooks) ClosePanel(string, string) {}
268
269// setupNonInteractiveExtensions loads --ext paths and (unless
270// --no-ext) runs discovery. Returns the manager so the caller can
271// wire tools into the resolved registry, and a cleanup closure to
272// defer. Mirrors the interactive-mode setup minus the TUI hooks.
273func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
274 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
275 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
276 fmt.Fprintln(os.Stderr, "extension load:", e)
277 }
278 if !args.NoExt {
279 for _, e := range extMgr.Discover(ctx) {
280 fmt.Fprintln(os.Stderr, "extension load:", e)
281 }
282 }
283 extMgr.WaitForReady(3 * time.Second)
284 r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
285 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
286 return extMgr, func() { extMgr.Stop(2 * time.Second) }
287}
288
289// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
290// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
291// interactive path wires up, so extensions get their normal
292// event-intercept surface in print / json / rpc flows too.
293func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
294 if ag == nil || extMgr == nil {
295 return
296 }
297 ag.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
298 res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
299 if res.Block {
300 return false, res.Reason, nil
301 }
302 return true, "", res.ModifiedArgs
303 }
304 ag.BeforeTurn = func(step int) (bool, string) {
305 res := extMgr.InterceptTurnStart(ctx, step)
306 return !res.Block, res.Reason
307 }
308 ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
309 res := extMgr.InterceptAssistantMessage(ctx, text)
310 if res.Block {
311 return false, res.Reason, ""
312 }
313 return true, "", res.ReplaceText
314 }
315 ag.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
316}
317
318func runPrintMode(ctx context.Context, args Args, version string) error {
319 if args.NoYolo {
320 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
321 }
322 r, err := Resolve(args, true)
323 if err != nil {
324 return err
325 }
326 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
327 defer stopExt()
328
329 ag := r.NewAgent()
330 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
331 sess, _ := openOrCreateSession(args, r, ag, version)
332 defer sess.Close()
333
334 prompt := args.Prompt
335 if prompt == "" {
336 piped, _ := readAllStdin()
337 prompt = strings.TrimSpace(piped)
338 }
339 if prompt == "" {
340 return fmt.Errorf("print mode requires a prompt (arg or stdin)")
341 }
342
343 start := len(ag.Messages())
344 err = modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
345 WriteNewTranscript(ag, sess, start)
346 return err
347}
348
349func runJSONMode(ctx context.Context, args Args, version string) error {
350 if args.NoYolo {
351 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
352 }
353 r, err := Resolve(args, true)
354 if err != nil {
355 return err
356 }
357 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
358 defer stopExt()
359
360 ag := r.NewAgent()
361 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
362 sess, _ := openOrCreateSession(args, r, ag, version)
363 defer sess.Close()
364
365 prompt := args.Prompt
366 if prompt == "" {
367 piped, _ := readAllStdin()
368 prompt = strings.TrimSpace(piped)
369 }
370 if prompt == "" {
371 return fmt.Errorf("json mode requires a prompt (arg or stdin)")
372 }
373
374 start := len(ag.Messages())
375 err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
376 WriteNewTranscript(ag, sess, start)
377 return err
378}
379
380// ---- interactive mode: opens the TUI even without credentials ----
381
382func runInteractive(ctx context.Context, args Args, version string) error {
383 // Resolve WITHOUT requiring credentials.
384 r, err := Resolve(args, false)
385 if err != nil {
386 return err
387 }
388
389 authStore := AuthStoreFor()
390 mgr := auth.NewManager(authStore)
391 defer mgr.Close()
392
393 // Keep the sandbox pointer stable across agent rebuilds (login / model
394 // switch). The Interactive UI toggles the lock via this pointer, and
395 // rebuilt tool instances must share the same one so the lock sticks.
396 sharedSandbox := r.Sandbox
397
398 // Build the extension manager BEFORE the agent so we can fold
399 // extension-defined tools into the registry. Forward-declare iv so
400 // the host hooks adapter can dereference it after construction.
401 var iv *modes.Interactive
402 extHooks := &interactiveExtHooks{ivPtr: &iv}
403 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
404 // --ext paths first so they win against installed extensions of
405 // the same name (loadOne's first-write-wins semantics).
406 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
407 fmt.Fprintln(os.Stderr, "extension load:", e)
408 }
409 // --no-ext skips the global + project-local discovery scan;
410 // explicit --ext paths above are still honoured so you can run
411 // "only this extension" with --no-ext --ext ./x.
412 if !args.NoExt {
413 for _, e := range extMgr.Discover(ctx) {
414 fmt.Fprintln(os.Stderr, "extension load:", e)
415 }
416 }
417 // Wait briefly for extensions to flush their initial register_tool
418 // frames before we build the agent's tool registry. Half a second
419 // is plenty for any extension that's actually well-behaved; ones
420 // that don't send a ready frame eat the full grace and proceed.
421 // 3s is the per-extension grace period for the ready frame.
422 // Native binaries are instant; runtimes like `npx tsx` take ~1.5s
423 // from cold cache. The wait is tight only for extensions that
424 // haven't sent ready by then; ones that signalled earlier release
425 // the wait immediately.
426 extMgr.WaitForReady(3 * time.Second)
427 defer extMgr.Stop(2 * time.Second)
428
429 extToolAdapter := &extToolAdapter{mgr: extMgr}
430 r.MergeExtensionTools(extToolAdapter)
431
432 // Build the swarm supervisor BEFORE the agent so the auto-swarm
433 // tool can reference it during tool-registry construction. State
434 // lives under ZotHome/swarm so per-agent meta/events survive
435 // restarts; the user can hunt orphaned agents down with
436 // `git worktree list` if anything misbehaves.
437 //
438 // swarmMgr is also captured by loadSession / changeCWD closures
439 // further down the function, which is why we keep the variable
440 // in this outer scope rather than scoping it tighter.
441 var swarmMgr *swarm.Swarm
442 swarmMgr = swarm.New(swarm.Config{
443 Root: filepath.Join(ZotHome(), "swarm"),
444 RepoRoot: r.CWD,
445 })
446 // Pull any previously-spawned agents off disk so the dashboard
447 // shows them as detached and the user can resume / remove them.
448 _, _ = swarmMgr.Reload()
449
450 // onSpawnedSwarm is the OnSpawned callback the swarm_spawn tool
451 // fires after every successful spawn. It hands the agent off to
452 // the running Interactive so the watcher can flush a summary back
453 // into chat when all sub-agents finish. Reads `iv` lazily because
454 // the Interactive is constructed after the agent.
455 onSpawnedSwarm := func(a *swarm.Agent, task string) {
456 if iv != nil {
457 iv.TrackSwarmAgent(a, task)
458 }
459 }
460
461 // Inject the swarm_spawn auto-swarm tool only when /settings ->
462 // auto-swarm is currently enabled. Registering it unconditionally
463 // leaves the model trying to call it (and getting a polite error)
464 // even when the user has switched the feature off. The /settings
465 // toggle live-mutates the running agent's registry separately so
466 // flipping the flag mid-session takes effect on the next turn.
467 injectSwarmSpawn := func(reg core.Registry) core.Registry {
468 if reg == nil {
469 return reg
470 }
471 if !AutoSwarmEnabled() {
472 return reg
473 }
474 reg["swarm_spawn"] = &tools.SwarmSpawnTool{
475 Swarm: swarmMgr,
476 Enabled: AutoSwarmEnabled,
477 OnSpawned: onSpawnedSwarm,
478 }
479 return reg
480 }
481 injectSwarmSpawn(r.ToolRegistry)
482
483 // Confirmation gate: when --no-yolo is on, the agent must ask
484 // the user before every tool call. In interactive mode the TUI
485 // provides the Confirmer; in print/json/rpc modes there's no
486 // way to prompt, so the gate is constructed with a nil inner
487 // which auto-refuses every call with a helpful reason.
488 var confirmGate *core.ConfirmGate
489 if args.NoYolo {
490 confirmGate = core.NewConfirmGate(nil) // set below for interactive
491 }
492
493 // Capture current args in a closure so BuildAgent can re-resolve
494 // after a successful login (picks up the newly stored credential).
495 wireAgentExt := func(a *core.Agent) *core.Agent {
496 if a == nil {
497 return a
498 }
499 a.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
500 // Confirm gate runs FIRST: if the user refused, we don't
501 // waste extension-intercept time or let guards see the call.
502 if confirmGate != nil {
503 ok, reason, _ := confirmGate.Check(call.Name, core.BuildPreview(call.Arguments, 120))
504 if !ok {
505 return false, reason, nil
506 }
507 }
508 r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
509 if r.Block {
510 return false, r.Reason, nil
511 }
512 return true, "", r.ModifiedArgs
513 }
514 a.BeforeTurn = func(step int) (bool, string) {
515 r := extMgr.InterceptTurnStart(ctx, step)
516 return !r.Block, r.Reason
517 }
518 a.BeforeAssistantMessage = func(text string) (bool, string, string) {
519 r := extMgr.InterceptAssistantMessage(ctx, text)
520 if r.Block {
521 return false, r.Reason, ""
522 }
523 return true, "", r.ReplaceText
524 }
525 a.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
526 return a
527 }
528
529 buildAgent := func() (*core.Agent, string, string, error) {
530 resolved, err := Resolve(args, true)
531 if err != nil {
532 return nil, "", "", err
533 }
534 resolved.UseSandbox(sharedSandbox)
535 resolved.MergeExtensionTools(extToolAdapter)
536 injectSwarmSpawn(resolved.ToolRegistry)
537 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
538 }
539
540 // Rebuild agent with an explicit provider/model override.
541 buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
542 next := args
543 if providerOverride != "" {
544 next.Provider = providerOverride
545 }
546 if modelOverride != "" {
547 next.Model = modelOverride
548 }
549 resolved, err := Resolve(next, true)
550 if err != nil {
551 return nil, "", "", err
552 }
553 resolved.UseSandbox(sharedSandbox)
554 resolved.MergeExtensionTools(extToolAdapter)
555 injectSwarmSpawn(resolved.ToolRegistry)
556 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
557 }
558
559 // Rebuild agent for the rescue picker after a recoverable failure.
560 // Unlike buildAgentFor, this drops launch-time --api-key and
561 // --base-url overrides because those are typically the cause of the
562 // rescue (a bad key, a typo'd base URL, or a corporate gateway that
563 // only the originally-picked provider needed). Re-resolving without
564 // them lets the rescue retry use env vars / auth.json / provider
565 // defaults the way zot would have without the overrides.
566 buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
567 next := args
568 next.APIKey = ""
569 next.BaseURL = ""
570 if providerOverride != "" {
571 next.Provider = providerOverride
572 }
573 if modelOverride != "" {
574 next.Model = modelOverride
575 }
576 resolved, err := Resolve(next, true)
577 if err != nil {
578 return nil, "", "", err
579 }
580 resolved.UseSandbox(sharedSandbox)
581 resolved.MergeExtensionTools(extToolAdapter)
582 injectSwarmSpawn(resolved.ToolRegistry)
583 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
584 }
585
586 var ag *core.Agent
587 if r.HasCredential() {
588 ag = wireAgentExt(r.NewAgent())
589 }
590
591 // /reload-ext callback: after the manager has respawned every
592 // extension, re-resolve the tool registry (built-ins + freshly-
593 // registered extension tools) and swap it onto the current
594 // agent in-place. The current agent may have been replaced by a
595 // /model swap since spawn, so re-read the live `ag` on each
596 // invocation.
597 extMgr.SetOnReload(func() {
598 current := ag
599 if current == nil {
600 return
601 }
602 resolved, err := Resolve(args, true)
603 if err != nil {
604 return
605 }
606 resolved.UseSandbox(sharedSandbox)
607 resolved.MergeExtensionTools(extToolAdapter)
608 injectSwarmSpawn(resolved.ToolRegistry)
609 current.SetTools(resolved.ToolRegistry)
610 })
611
612 // Fire session_start once we know the manager's running.
613 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
614
615 var sess *core.Session
616 var sessBaselineMsgs int // messages already on disk when current session opened
617 // persistMu guards sess + sessBaselineMsgs against concurrent access
618 // from the agent loop's per-message persistence hook (runs on the
619 // agent goroutine) and the TUI's session swap / flush callbacks
620 // (run on the TUI goroutine). Without this, a /sessions swap that
621 // races with a finishing turn could double-write or lose messages.
622 var persistMu sync.Mutex
623 if !args.NoSess && ag != nil {
624 sess, _ = openOrCreateSession(args, r, ag, version)
625 if ag != nil {
626 sessBaselineMsgs = len(ag.Messages())
627 }
628 }
629 defer func() {
630 persistMu.Lock()
631 defer persistMu.Unlock()
632 if sess != nil {
633 sess.Close()
634 }
635 }()
636
637 // persistMessage is the per-message hook bound to the agent. It
638 // appends each new transcript message to the live session as soon
639 // as it lands, so a kill / closed terminal / OS crash costs at
640 // most the in-flight turn instead of the whole session. The
641 // baseline counter advances in lock-step so the exit-time flush
642 // doesn't double-write rows already on disk.
643 persistMessage := func(m provider.Message) {
644 persistMu.Lock()
645 defer persistMu.Unlock()
646 if sess == nil {
647 return
648 }
649 if err := sess.AppendMessage(m); err == nil {
650 sessBaselineMsgs++
651 }
652 }
653 persistUsage := func(cum provider.Usage) {
654 persistMu.Lock()
655 defer persistMu.Unlock()
656 if sess == nil {
657 return
658 }
659 _ = sess.AppendUsage(cum, cum)
660 }
661 persistCompaction := func(messages []provider.Message) {
662 persistMu.Lock()
663 defer persistMu.Unlock()
664 if sess == nil {
665 return
666 }
667 if err := sess.AppendCompaction(messages); err == nil {
668 sessBaselineMsgs = len(messages)
669 }
670 }
671 wireAgentPersist := func(a *core.Agent) *core.Agent {
672 if a == nil {
673 return a
674 }
675 a.OnMessageAppended = persistMessage
676 a.OnUsage = persistUsage
677 a.OnTranscriptCompacted = persistCompaction
678 return a
679 }
680 wireAgentPersist(ag)
681
682 // Re-wrap the build closures so any agent constructed by the TUI
683 // (login, /model swap to a different provider) also gets the
684 // persistence hooks. Without this, switching provider would
685 // silently revert to the old in-memory-only behaviour.
686 baseBuildAgent := buildAgent
687 buildAgent = func() (*core.Agent, string, string, error) {
688 a, p, m, err := baseBuildAgent()
689 return wireAgentPersist(a), p, m, err
690 }
691 baseBuildAgentFor := buildAgentFor
692 buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
693 a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
694 return wireAgentPersist(a), p, m, err
695 }
696 baseBuildAgentForRescue := buildAgentForRescue
697 buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
698 a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
699 return wireAgentPersist(a), p, m, err
700 }
701
702 // loadSession replaces the current session with the one at path and
703 // hands its messages to the agent. Used by the /sessions picker.
704 loadSession := func(path string) error {
705 currentAg := ag // captured
706 if currentAg == nil {
707 return fmt.Errorf("no agent running; log in first")
708 }
709 newSess, msgs, err := core.OpenSession(path)
710 if err != nil {
711 return err
712 }
713 fullMsgCount := len(msgs)
714 msgs = trimMessagesForResume(msgs, 100)
715 persistMu.Lock()
716 // Flush any unsaved messages to the old session before swapping.
717 // Per-message persistence keeps sessBaselineMsgs current, so
718 // this is a defensive no-op in the common case; it still
719 // matters for the rare race where a turn just finished and
720 // hadn't fired its hook yet.
721 if sess != nil {
722 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
723 _ = sess.Close()
724 }
725 sess = newSess
726 currentAg.SetMessages(msgs)
727 if cum, last, uerr := core.SessionUsageDetail(path); uerr == nil {
728 currentAg.SeedCost(cum)
729 currentAg.SeedLastTurnUsage(last)
730 }
731 // The live agent only receives a compact resume window, but
732 // the session file remains intact. Keep the persistence
733 // baseline at the original on-disk message count so future
734 // turns append after the full session instead of duplicating
735 // the hydrated tail.
736 sessBaselineMsgs = fullMsgCount
737 persistMu.Unlock()
738 // Re-scope the swarm dashboard to the new session so /swarm
739 // only shows agents this session spawned. swarmMgr may be nil
740 // here if we haven't reached the construction site yet (it
741 // shouldn't be, since the interactive loop is what triggers
742 // loadSession, but the nil check is cheap insurance).
743 if swarmMgr != nil && newSess != nil {
744 swarmMgr.SetActiveSession(newSess.ID)
745 }
746 return nil
747 }
748
749 // changeCWD switches the running session to a new working directory.
750 // Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
751 // /cd slash command (which itself is only fired by the workspaces
752 // extension's panel-key Enter handler today; the user can type /cd
753 // directly but it's not in autocomplete / help / the README).
754 //
755 // Steps, in order:
756 // 1. resolve + validate the new path (~ expansion, abs/rel)
757 // 2. close the current session, flushing pending messages
758 // 3. mutate captured args.CWD + r.CWD so future buildAgent
759 // calls bind to the new cwd
760 // 4. re-root the shared sandbox («·«) so /jail follows the
761 // session into the new cwd instead of widening or silently
762 // dropping
763 // 5. rebuild the agent via buildAgent() so tools, AGENTS.md
764 // addendum, system prompt, sessions dir all bind correctly
765 // 6. open a fresh session in the new cwd's bucket
766 // 7. push the new state into the running Interactive
767 // 8. re-scope the swarm dashboard to the freshly-opened session
768 //
769 // The /jail state is preserved verbatim: if the sandbox was locked
770 // to the old cwd, it stays locked, just re-pointed at the new one.
771 changeCWD := func(path string) error {
772 if path == "" {
773 return fmt.Errorf("empty path")
774 }
775 // ~ expansion.
776 if path == "~" || strings.HasPrefix(path, "~/") {
777 home, herr := os.UserHomeDir()
778 if herr != nil || home == "" {
779 return fmt.Errorf("cannot expand ~: %v", herr)
780 }
781 if path == "~" {
782 path = home
783 } else {
784 path = filepath.Join(home, path[2:])
785 }
786 }
787 if !filepath.IsAbs(path) {
788 path = filepath.Join(args.CWD, path)
789 }
790 absPath, err := filepath.Abs(path)
791 if err != nil {
792 return err
793 }
794 info, err := os.Stat(absPath)
795 if err != nil {
796 return err
797 }
798 if !info.IsDir() {
799 return fmt.Errorf("not a directory: %s", absPath)
800 }
801
802 currentAg := ag
803 if currentAg == nil {
804 return fmt.Errorf("no agent running; log in first")
805 }
806
807 // Close the current session before we drop the reference.
808 // Per-message persistence keeps it current already; this is
809 // a defensive flush + final fsync via Close.
810 persistMu.Lock()
811 if sess != nil {
812 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
813 _ = sess.Close()
814 sess = nil
815 }
816 sessBaselineMsgs = 0
817 persistMu.Unlock()
818
819 // Mutate captured state so subsequent agent rebuilds and
820 // session opens see the new cwd.
821 wasJailed := sharedSandbox != nil && sharedSandbox.Locked()
822 args.CWD = absPath
823 r.CWD = absPath
824 if sharedSandbox != nil {
825 sharedSandbox.Root = absPath
826 if wasJailed {
827 sharedSandbox.Lock()
828 } else {
829 sharedSandbox.Unlock()
830 }
831 }
832
833 // Rebuild the agent so tools / AGENTS.md / system prompt
834 // re-bind to the new cwd. buildAgent() reads from args + r.
835 newAg, newProvider, newModel, berr := buildAgent()
836 if berr != nil {
837 return fmt.Errorf("rebuild agent: %v", berr)
838 }
839 ag = newAg
840
841 // Fresh session in the new cwd's bucket. We bypass
842 // openOrCreateSession's --continue / --resume branches
843 // because /cd's semantics are "start fresh here", matching
844 // what relaunching `zot --cwd <path>` would do today.
845 if !args.NoSess {
846 core.PruneEmptySessions(ZotHome(), absPath)
847 newSess, serr := core.NewSession(ZotHome(), absPath, newProvider, newModel, version)
848 if serr != nil {
849 return fmt.Errorf("open session in %s: %v", absPath, serr)
850 }
851 persistMu.Lock()
852 sess = newSess
853 sessBaselineMsgs = 0
854 persistMu.Unlock()
855 }
856
857 // Push the new state into the running Interactive.
858 if iv != nil {
859 iv.ApplyChangedCWD(newAg, newProvider, newModel, absPath)
860 }
861
862 // Re-scope the swarm dashboard to the new session.
863 if swarmMgr != nil && sess != nil {
864 swarmMgr.SetActiveSession(sess.ID)
865 }
866 return nil
867 }
868
869 term := tui.NewProcTerm()
870
871 // Kick off the async update check so the banner can appear when the
872 // http response eventually arrives (usually <1s on cached DNS). Map
873 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
874 updateCh := make(chan modes.UpdateInfo, 1)
875 go func() {
876 defer close(updateCh)
877 src := <-CheckForUpdateAsync(ZotHome(), version)
878 updateCh <- modes.UpdateInfo{
879 Current: src.Current,
880 Latest: src.Latest,
881 Available: src.Available,
882 URL: src.URL,
883 }
884 }()
885
886 // Changelog: when the running version differs from the last
887 // version whose release notes the user dismissed, fetch the
888 // release body from GitHub and have the TUI show it once. On
889 // first-ever launch (no prior LastChangelogShown), seed the
890 // stored version silently — don't dump release notes at someone
891 // who just installed.
892 changelogCh := make(chan modes.ChangelogPayload, 1)
893 go func() {
894 defer close(changelogCh)
895 cfg, _ := LoadConfig()
896 if cfg.LastChangelogShown == "" {
897 SeedChangelogVersion(version)
898 return
899 }
900 if !ShouldShowChangelog(version, cfg) {
901 return
902 }
903 info := <-FetchChangelogAsync(version)
904 if info.Body == "" {
905 return
906 }
907 // For dev builds (0.0.0), skip if the latest release was
908 // already shown (stored by the dismiss callback).
909 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
910 return
911 }
912 changelogCh <- modes.ChangelogPayload{
913 Version: info.Version,
914 Body: info.Body,
915 URL: info.URL,
916 }
917 }()
918
919 initialCfg, _ := LoadConfig()
920 theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
921 if themeErr != nil {
922 fmt.Fprintln(os.Stderr, "theme load:", themeErr)
923 if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
924 initialCfg.Theme = ""
925 _ = SaveConfig(initialCfg)
926 }
927 }
928
929 // swarmMgr was constructed and reloaded earlier (before the agent
930 // build, so the auto-swarm tool could capture it). Here we just
931 // scope the dashboard to the active host session so /swarm only
932 // shows agents this session spawned (and any pre-upgrade unscoped
933 // agents — see SnapshotAll docs). Updated again whenever the
934 // user swaps sessions via loadSession below.
935 if sess != nil {
936 swarmMgr.SetActiveSession(sess.ID)
937 }
938 // Best-effort shutdown on interactive exit: stop all running
939 // agents so they don't outlive their parent zot.
940 defer swarmMgr.StopAll()
941
942 iv = modes.NewInteractive(modes.InteractiveConfig{
943 Terminal: term,
944 Theme: theme,
945 InlineImagesEnabled: initialCfg.InlineImagesEnabled,
946 AutoSwarmEnabled: initialCfg.AutoSwarmEnabled,
947 ThemeName: initialCfg.Theme,
948 ExtensionThemes: extMgr.ThemeOptions,
949 AutoSwarmSystemAddendum: AutoSwarmSystemAddendum,
950 SettingsStore: configSettingsStore{},
951 Model: r.Model,
952 Provider: r.Provider,
953 AuthMethod: r.AuthMethod,
954 BaseURL: r.BaseURL,
955 Reasoning: r.Reasoning,
956 SystemPrompt: r.SystemPrompt,
957 Tools: r.ToolRegistry,
958 MaxSteps: r.MaxSteps,
959 CWD: r.CWD,
960 ZotHome: ZotHome(),
961 Version: version,
962 UpdateInfoChan: updateCh,
963 Sandbox: sharedSandbox,
964 Agent: ag,
965 InitialInput: args.Prompt,
966 AuthManager: mgr,
967 BuildAgent: buildAgent,
968 SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
969 BuildAgentFor: buildAgentFor,
970 BuildAgentForRescue: buildAgentForRescue,
971 LoggedInProviders: func() []string {
972 var out []string
973 seen := map[string]bool{}
974 for _, p := range knownProviders {
975 if _, _, err := ResolveCredential(p, ""); err == nil && !seen[p] {
976 out = append(out, p)
977 seen[p] = true
978 }
979 }
980 // Ollama models are always available (no auth needed).
981 if !seen["ollama"] {
982 out = append(out, "ollama")
983 }
984 return out
985 },
986 LoadSession: loadSession,
987 ChangeCWD: changeCWD,
988 CurrentSessionPath: func() string {
989 if sess == nil {
990 return ""
991 }
992 return sess.Path
993 },
994 FlushSession: func() {
995 // Append any not-yet-persisted agent messages to the
996 // current session file, then advance the baseline so
997 // the final WriteNewTranscript at exit doesn't write
998 // duplicates. Per-message persistence keeps the on-
999 // disk file current already, so this is mostly a
1000 // defensive flush — still needed for /session export
1001 // to guarantee the exported bytes include the very
1002 // last in-flight turn.
1003 currentAg := iv.Agent()
1004 if currentAg == nil {
1005 return
1006 }
1007 persistMu.Lock()
1008 defer persistMu.Unlock()
1009 if sess == nil {
1010 return
1011 }
1012 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1013 sessBaselineMsgs = len(currentAg.Messages())
1014 },
1015 Extensions: extMgr,
1016 Swarm: swarmMgr,
1017 ChangelogChan: changelogCh,
1018 OnChangelogDismiss: func() {
1019 // For dev builds (0.0.0) store the actual release version
1020 // so the same changelog doesn't show again next launch.
1021 // For real builds, store the binary version.
1022 v := version
1023 if v == "0.0.0" {
1024 if iv != nil && iv.ChangelogVersion() != "" {
1025 v = iv.ChangelogVersion()
1026 }
1027 }
1028 _ = MarkChangelogShown(v)
1029 },
1030 SkillSnapshot: func() []*skills.Skill {
1031 if args.NoSkill {
1032 // --no-skill: nothing for the picker to show.
1033 return nil
1034 }
1035 // Re-discover so the picker reflects edits made during
1036 // the session. Cheap; SKILL.md files are small. Filter
1037 // out built-in skills — they're hidden from user-facing
1038 // surfaces because they're implementation detail; the
1039 // model still sees them through the system-prompt
1040 // manifest and the skill tool.
1041 userHome, _ := os.UserHomeDir()
1042 list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
1043 return skills.VisibleSkills(list)
1044 },
1045 NoYolo: args.NoYolo,
1046 ConfirmGate: confirmGate,
1047 PersistModel: func(providerName, model string) {
1048 // Update config.json so next launch uses the same pick.
1049 cfg, _ := LoadConfig()
1050 cfg.Provider = providerName
1051 cfg.Model = model
1052 _ = SaveConfig(cfg)
1053 // Update the active session's meta so resume picks this up.
1054 if sess != nil {
1055 _ = sess.UpdateModel(providerName, model)
1056 }
1057 },
1058 })
1059
1060 // Bind the interactive TUI as the Confirmer. We deferred this
1061 // until now because the gate is constructed before the TUI
1062 // (the BeforeToolExecute closure captures it). SetConfirmer
1063 // is mutex-guarded on the gate so this is safe.
1064 if confirmGate != nil {
1065 confirmGate.SetConfirmer(iv)
1066 }
1067
1068 // Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1069 // (closed terminal window, system shutdown, kill) used to lose
1070 // the entire in-memory transcript because the deferred post-Run
1071 // flush below never ran. Per-message persistence above covers
1072 // most of it; this handler writes any in-flight remainder and
1073 // then exits the process so we don't double-paint over a
1074 // broken terminal that the TUI's restore deferreds can no
1075 // longer fix from a signal context.
1076 //
1077 // SIGINT is intentionally NOT handled here — the TUI consumes
1078 // Ctrl+C as a regular key event for cancel/clear semantics, and
1079 // installing a SIGINT notifier here would swallow it.
1080 sigCh := make(chan os.Signal, 1)
1081 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1082 defer signal.Stop(sigCh)
1083 go func() {
1084 _, ok := <-sigCh
1085 if !ok {
1086 return
1087 }
1088 if finalAg := iv.Agent(); finalAg != nil {
1089 persistMu.Lock()
1090 if sess != nil {
1091 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1092 sessBaselineMsgs = len(finalAg.Messages())
1093 _ = sess.Close()
1094 sess = nil
1095 }
1096 persistMu.Unlock()
1097 }
1098 // Exit cleanly. Re-raising the signal would skip os.Exit's
1099 // at-exit hooks; explicit exit is fine because we've already
1100 // flushed the only at-risk state (the session file).
1101 os.Exit(0)
1102 }()
1103
1104 runErr := iv.Run(ctx)
1105
1106 // Flush final transcript to session (only if we had / ended up with an agent).
1107 if finalAg := iv.Agent(); finalAg != nil {
1108 persistMu.Lock()
1109 if sess != nil {
1110 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1111 sessBaselineMsgs = len(finalAg.Messages())
1112 }
1113 persistMu.Unlock()
1114 }
1115 return runErr
1116}
1117
1118// openOrCreateSession returns a session for the run. sess may be nil
1119// with a nil error if session persistence is disabled.
1120func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1121 if args.NoSess {
1122 return nil, nil
1123 }
1124 // Sweep meta-only files left over from older zot versions (and from
1125 // any session that crashed before its first AppendMessage). Cheap;
1126 // reads the first few bytes of each file in the cwd's session dir.
1127 core.PruneEmptySessions(ZotHome(), args.CWD)
1128 var (
1129 s *core.Session
1130 msgs []provider.Message
1131 err error
1132 )
1133 switch {
1134 case args.Session != "":
1135 s, msgs, err = core.OpenSession(args.Session)
1136 // The swarm-agent child passes a fixed --session path that
1137 // may not exist yet on first Spawn. Treat ENOENT as "create
1138 // a fresh session AT THIS PATH" so the conversation actually
1139 // gets persisted; without this fallback the swarm child runs
1140 // with sess==nil and every Resume re-starts with no memory
1141 // of the prior turns. Other openers (--continue / --resume /
1142 // the picker) never see ENOENT here because they only choose
1143 // paths that already exist on disk.
1144 if err != nil && errors.Is(err, os.ErrNotExist) {
1145 s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1146 msgs = nil
1147 }
1148 case args.Continue:
1149 latest := core.LatestSession(ZotHome(), args.CWD)
1150 if latest != "" {
1151 s, msgs, err = core.OpenSession(latest)
1152 }
1153 case args.Resume:
1154 picked, perr := pickSession(args.CWD)
1155 if perr != nil {
1156 return nil, perr
1157 }
1158 if picked != "" {
1159 s, msgs, err = core.OpenSession(picked)
1160 }
1161 }
1162 if err != nil {
1163 return nil, err
1164 }
1165 if s != nil {
1166 ag.SetMessages(msgs)
1167 if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1168 ag.SeedCost(cum)
1169 ag.SeedLastTurnUsage(last)
1170 }
1171 return s, nil
1172 }
1173 return core.NewSession(ZotHome(), args.CWD, r.Provider, r.Model, version)
1174}
1175
1176func pickSession(cwd string) (string, error) {
1177 files := core.ListSessions(ZotHome(), cwd)
1178 if len(files) == 0 {
1179 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1180 return "", nil
1181 }
1182 for i, f := range files {
1183 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
1184 }
1185 fmt.Fprint(os.Stderr, "pick #: ")
1186 rd := bufio.NewReader(os.Stdin)
1187 line, _ := rd.ReadString('\n')
1188 line = strings.TrimSpace(line)
1189 var n int
1190 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1191 return "", fmt.Errorf("invalid selection")
1192 }
1193 return files[n-1], nil
1194}
1195
1196// WriteNewTranscript appends only messages after index `from` from the
1197// agent's transcript to the session. Used by callers that don't hold
1198// the persistMu (non-interactive print/json modes which run a single
1199// turn under their own goroutine).
1200func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1201 writeNewTranscriptLocked(ag, sess, from)
1202}
1203
1204// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1205// suffix marks that interactive callers must hold persistMu when
1206// invoking it so concurrent appends from the agent loop don't race
1207// with this catch-up flush.
1208func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1209 if sess == nil || ag == nil {
1210 return
1211 }
1212 msgs := ag.Messages()
1213 for i := from; i < len(msgs); i++ {
1214 _ = sess.AppendMessage(msgs[i])
1215 }
1216 cum := ag.Cost()
1217 _ = sess.AppendUsage(cum, cum)
1218}
1219
1220func readAllStdin() (string, error) {
1221 fi, err := os.Stdin.Stat()
1222 if err != nil {
1223 return "", err
1224 }
1225 if (fi.Mode() & os.ModeCharDevice) != 0 {
1226 return "", nil
1227 }
1228 b, err := io.ReadAll(os.Stdin)
1229 return string(b), err
1230}
1231
1232func printModels() {
1233 models := provider.Active()
1234
1235 // Compute column widths from actual data so wide providers (e.g.
1236 // xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1237 // `name` column off-screen. Floors mirror the historical layout so
1238 // short catalogs look the same as before.
1239 provW, idW, srcW := len("provider"), len("model id"), len("source")
1240 for _, m := range models {
1241 if w := len(m.Provider); w > provW {
1242 provW = w
1243 }
1244 if w := len(m.ID); w > idW {
1245 idW = w
1246 }
1247 source := m.Source
1248 if source == "" {
1249 source = "catalog"
1250 }
1251 if m.Speculative {
1252 source = "speculative"
1253 }
1254 if w := len(source); w > srcW {
1255 srcW = w
1256 }
1257 }
1258
1259 header := fmt.Sprintf("%-*s %-*s %8s %8s %s %-*s %s",
1260 provW, "provider",
1261 idW, "model id",
1262 "context", "max-out", "reasoning",
1263 srcW, "source",
1264 "name")
1265 fmt.Println(header)
1266
1267 for _, m := range models {
1268 reason := " "
1269 if m.Reasoning {
1270 reason = "✓"
1271 }
1272 source := m.Source
1273 if source == "" {
1274 source = "catalog"
1275 }
1276 if m.Speculative {
1277 source = "speculative"
1278 }
1279 fmt.Printf("%-*s %-*s %8d %8d %s %-*s %s\n",
1280 provW, m.Provider,
1281 idW, m.ID,
1282 m.ContextWindow, m.MaxOutput,
1283 reason,
1284 srcW, source,
1285 m.DisplayName)
1286 }
1287}