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.SubmitOrQueue(text, nil)
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 Deferred: t.Deferred,
110 }
111 }
112 return out
113}
114
115func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
116 return extensions.NewTool(a.mgr, extensions.ToolInfo{
117 Extension: info.Extension,
118 Name: info.Name,
119 Description: info.Description,
120 Schema: info.Schema,
121 Deferred: info.Deferred,
122 })
123}
124
125// liveInteractiveAgent returns the agent currently owned by the TUI. The
126// fallback is only used before the Interactive has been constructed.
127//
128// Agent rebuilds, such as cross-provider model switches, replace the TUI's
129// agent without replacing the startup pointer held by runInteractive. Session
130// operations must therefore resolve the live agent at the time of the action.
131func liveInteractiveAgent(iv *modes.Interactive, fallback *core.Agent) *core.Agent {
132 if iv != nil {
133 return iv.Agent()
134 }
135 return fallback
136}
137
138func trimMessagesForResume(msgs []provider.Message, keepTail int) []provider.Message {
139 if keepTail <= 0 || len(msgs) <= keepTail {
140 return provider.RepairOrphanedToolResults(msgs)
141 }
142 var out []provider.Message
143 start := len(msgs) - keepTail
144 // Preserve the synthetic compaction summary when present so an
145 // already-compacted session stays compacted after resume.
146 if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" && start > 1 {
147 out = append(out, msgs[0])
148 }
149 // Avoid hydrating a tail that starts with orphan tool_result rows;
150 // provider APIs require those to be paired with an earlier tool_use.
151 for start < len(msgs) && msgs[start].Role == provider.RoleTool {
152 start++
153 }
154 out = append(out, msgs[start:]...)
155 return provider.RepairOrphanedToolResults(out)
156}
157
158// fanoutAgentEvent translates a core.AgentEvent into the wire-format
159// EventFromHost and pushes it through the extension manager. Only
160// the events that have a clear extension-facing meaning are
161// forwarded; internal-only ones (text_delta, tool_progress) are
162// dropped to keep the per-extension stream sane.
163func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
164 if mgr == nil {
165 return
166 }
167 switch e := ev.(type) {
168 case core.EvPromptSubmit:
169 mgr.EmitEvent(extproto.EventFromHost{Event: "user_prompt_submit", Text: e.Text, Queued: e.Queued, ImageCount: e.ImageCount})
170 case core.EvToolResult:
171 if e.Executed && e.Status == "blocked" {
172 mgr.EmitEvent(extproto.EventFromHost{Event: "permission_decision", ToolID: e.ID, ToolName: e.Name, Decision: "denied", Source: "policy", Stage: "tool_execution"})
173 }
174 mgr.EmitEvent(extproto.EventFromHost{Event: "tool_result", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args, Status: e.Status, Executed: &e.Executed, Result: extensionEventResult(e.Result)})
175 case core.EvCompact:
176 event := extproto.EventFromHost{Event: e.Type(), CompactionID: e.ID, MessageCount: &e.MessageCount, TokenEstimate: &e.TokenEstimate, Status: e.Status}
177 if e.Err != nil {
178 event.Error = e.Err.Error()
179 }
180 mgr.EmitEvent(event)
181 case core.EvTurnStart:
182 mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
183 case core.EvToolCall:
184 mgr.EmitEvent(extproto.EventFromHost{
185 Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
186 })
187 case core.EvAssistantMessage:
188 // Concat the visible text portions of the message; binary
189 // blocks (tool_use, etc.) are skipped because subscribers
190 // usually want a string they can grep / display.
191 var text string
192 for _, c := range e.Message.Content {
193 if tb, ok := c.(provider.TextBlock); ok {
194 text += tb.Text
195 }
196 }
197 mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
198 case core.EvTurnEnd:
199 ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
200 if e.Err != nil {
201 ev.Error = e.Err.Error()
202 }
203 mgr.EmitEvent(ev)
204 }
205}
206
207// Run is the top-level entrypoint for the zot binary.
208func Run(rawArgs []string, version string) error {
209 // Apply network configuration before any subcommand can make an HTTP
210 // request. Standard proxy environment variables retain precedence.
211 applyConfiguredHTTPProxy()
212
213 // Subcommand router: `zot bot ...` is handled separately so the
214 // generic flag parser doesn't reject "bot" as a positional arg.
215 if handled, err := runBotCommand(rawArgs, version); handled {
216 return err
217 }
218 if handled, err := runExtCommand(rawArgs, version); handled {
219 return err
220 }
221 if handled, err := runUpdateCommand(rawArgs, version); handled {
222 return err
223 }
224 if handled, err := runSessionsCommand(rawArgs); handled {
225 return err
226 }
227 if handled, err := runZotfileCommand(rawArgs, version); handled {
228 return err
229 }
230 return runWithArgsRaw(rawArgs, version)
231}
232
233func runWithArgsRaw(rawArgs []string, version string) error {
234 // `zot rpc` is shorthand for `zot --rpc` so third-party apps can
235 // spawn the binary with a clean argv. Strip the leading 'rpc'
236 // token and let the rest flow through the normal arg parser.
237 if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
238 rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
239 }
240
241 if fi, err := os.Stdin.Stat(); err == nil {
242 rawArgs = argsForStdin(rawArgs, fi.Mode())
243 }
244 args, err := ParseArgs(rawArgs)
245 if err != nil {
246 PrintHelp(version)
247 return err
248 }
249 if args.Help {
250 printHelp(os.Stdout, version)
251 return nil
252 }
253 if args.Version {
254 fmt.Println("zot", version)
255 return nil
256 }
257 // Model catalog: load any cached discovery data before we inspect
258 // the model list (list-models, print/json, interactive).
259 prepareRuntimeCatalog()
260
261 if args.ListModels {
262 printModels()
263 return nil
264 }
265
266 return runWithArgs(args, version)
267}
268
269func runWithArgs(args Args, version string) error {
270 ctx := context.Background()
271 switch args.Mode {
272 case ModePrint:
273 return runPrintMode(ctx, args, version)
274 case ModeStream:
275 return runStreamMode(ctx, args, version)
276 case ModeJSON:
277 return runJSONMode(ctx, args, version)
278 case ModeRPC:
279 return runRPCMode(ctx, args, version)
280 case ModeSwarmAgent:
281 return runSwarmAgentMode(ctx, args, version)
282 default:
283 return runInteractive(ctx, args, version)
284 }
285}
286
287// ---- print / json modes: require credentials, run single-shot ----
288
289// nonInteractiveExtHooks is the HostHooks impl used by print / json
290// modes. They have no TUI, so notify / display go to stderr and
291// submit / insert are no-ops (the extension can't steer a
292// single-shot run once it's in flight anyway).
293type nonInteractiveExtHooks struct{}
294
295func (nonInteractiveExtHooks) Notify(ext, level, message string) {
296 fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
297}
298func (nonInteractiveExtHooks) Submit(string) {}
299func (nonInteractiveExtHooks) SubmitSlash(string) {}
300func (nonInteractiveExtHooks) Insert(string) {}
301func (nonInteractiveExtHooks) Display(string, string) {}
302func (nonInteractiveExtHooks) ClearNotes(string) {}
303func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec) {}
304func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
305func (nonInteractiveExtHooks) ClosePanel(string, string) {}
306
307// setupNonInteractiveExtensions loads --ext paths and (unless
308// --no-ext) runs discovery. Returns the manager so the caller can
309// wire tools into the resolved registry, and a cleanup closure to
310// defer. Mirrors the interactive-mode setup minus the TUI hooks.
311func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
312 reportSkillDiagnostics(os.Stderr, r.SkillDiagnostics)
313 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
314 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
315 fmt.Fprintln(os.Stderr, "extension load:", e)
316 }
317 if !args.NoExt {
318 for _, e := range extMgr.Discover(ctx) {
319 fmt.Fprintln(os.Stderr, "extension load:", e)
320 }
321 }
322 extMgr.WaitForReady(3 * time.Second)
323 r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
324 return extMgr, func() { extMgr.Stop(2 * time.Second) }
325}
326
327func reportSkillDiagnostics(w io.Writer, diagnostics []string) {
328 for _, diagnostic := range diagnostics {
329 fmt.Fprintln(w, "skill discovery:", diagnostic)
330 }
331}
332
333// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
334// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
335// interactive path wires up, so extensions get their normal
336// event-intercept surface in print / json / rpc flows too.
337func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
338 if ag == nil || extMgr == nil {
339 return
340 }
341 wireBeforeAgentStart(ag, extMgr, "")
342 ag.BeforeToolExecuteContext = func(ctx context.Context, call provider.ToolCallBlock) (bool, string, json.RawMessage) {
343 res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
344 if res.Block {
345 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: res.Reason})
346 return false, res.Reason, res.ModifiedArgs
347 }
348 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Allow: true, Source: "yolo"})
349 return true, "", res.ModifiedArgs
350 }
351 ag.BeforeTurn = func(step int) (bool, string) {
352 res := extMgr.InterceptTurnStart(ctx, step)
353 return !res.Block, res.Reason
354 }
355 ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
356 res := extMgr.InterceptAssistantMessage(ctx, text)
357 if res.Block {
358 return false, res.Reason, ""
359 }
360 return true, "", res.ReplaceText
361 }
362 wireLifecycleEvents(ag, extMgr)
363}
364
365type printStats struct {
366 Provider string `json:"provider"`
367 Model string `json:"model"`
368 PromptTokens int `json:"prompt_tokens"`
369 ReasoningTokens *int `json:"reasoning_tokens"`
370 GeneratedOutputTokens int `json:"generated_output_tokens"`
371 ElapsedMS int64 `json:"elapsed_ms"`
372}
373
374func writePrintStats(path, providerID, model string, usage provider.Usage, elapsed time.Duration) error {
375 var reasoning *int
376 generated := usage.OutputTokens
377 if usage.ReasoningTokensKnown {
378 count := usage.ReasoningTokens
379 reasoning = &count
380 generated -= count
381 if generated < 0 {
382 generated = 0
383 }
384 }
385 stats := printStats{
386 Provider: providerID,
387 Model: model,
388 PromptTokens: usage.InputTokens + usage.CacheReadTokens + usage.CacheWriteTokens,
389 ReasoningTokens: reasoning,
390 GeneratedOutputTokens: generated,
391 ElapsedMS: elapsed.Milliseconds(),
392 }
393 data, err := json.MarshalIndent(stats, "", " ")
394 if err != nil {
395 return fmt.Errorf("encode stats: %w", err)
396 }
397 data = append(data, '\n')
398 if err := os.WriteFile(path, data, 0o644); err != nil {
399 return fmt.Errorf("write stats %q: %w", path, err)
400 }
401 return nil
402}
403
404func runPrintMode(ctx context.Context, args Args, version string) error {
405 if args.NoYolo {
406 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
407 }
408 r, err := Resolve(args, true)
409 if err != nil {
410 return err
411 }
412 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
413 defer stopExt()
414
415 ag := r.NewAgent()
416 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
417 sess, _ := openOrCreateSession(args, r, ag, version)
418 defer sess.Close()
419
420 piped, _ := readAllStdin()
421 prompt := combinePromptInput(piped, args.Prompt)
422 if prompt == "" {
423 return fmt.Errorf("print mode requires a prompt (arg or stdin)")
424 }
425
426 start := len(ag.Messages())
427 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, nil, os.Stderr); err != nil {
428 return err
429 }
430 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
431 started := time.Now()
432 usage, err := modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
433 elapsed := time.Since(started)
434 WriteNewTranscript(ag, sess, start)
435 if err != nil {
436 return err
437 }
438 if args.StatsPath != "" {
439 return writePrintStats(args.StatsPath, r.Provider, r.Model, usage, elapsed)
440 }
441 return nil
442}
443
444func runStreamMode(ctx context.Context, args Args, version string) error {
445 if args.NoYolo {
446 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in stream mode (no interactive prompt available); tools will run without confirmation")
447 }
448 r, err := Resolve(args, true)
449 if err != nil {
450 return err
451 }
452 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
453 defer stopExt()
454
455 ag := r.NewAgent()
456 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
457 sess, _ := openOrCreateSession(args, r, ag, version)
458 defer sess.Close()
459
460 piped, _ := readAllStdin()
461 prompt := combinePromptInput(piped, args.Prompt)
462 if prompt == "" {
463 return fmt.Errorf("stream mode requires a prompt (arg or stdin)")
464 }
465
466 start := len(ag.Messages())
467 preSink, finishPre := newStreamTextSink(os.Stdout)
468 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
469 finishPre()
470 return err
471 }
472 finishPre()
473 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
474 err = modes.RunStream(ctx, ag, prompt, nil, os.Stdout)
475 WriteNewTranscript(ag, sess, start)
476 return err
477}
478
479func newStreamTextSink(out io.Writer) (func(core.AgentEvent), func()) {
480 var streamed, wroteText, lastWasNL bool
481 writeText := func(text string) {
482 if text == "" {
483 return
484 }
485 _, _ = fmt.Fprint(out, text)
486 if syncer, ok := out.(interface{ Sync() error }); ok {
487 _ = syncer.Sync()
488 }
489 wroteText = true
490 lastWasNL = strings.HasSuffix(text, "\n")
491 }
492 sink := func(ev core.AgentEvent) {
493 switch e := ev.(type) {
494 case core.EvAssistantStart:
495 streamed = false
496 case core.EvTextDelta:
497 streamed = true
498 writeText(e.Delta)
499 case core.EvAssistantMessage:
500 if streamed {
501 return
502 }
503 var text strings.Builder
504 for _, content := range e.Message.Content {
505 if block, ok := content.(provider.TextBlock); ok {
506 if text.Len() > 0 {
507 text.WriteString("\n")
508 }
509 text.WriteString(block.Text)
510 }
511 }
512 writeText(text.String())
513 }
514 }
515 finish := func() {
516 if wroteText && !lastWasNL {
517 writeText("\n")
518 }
519 }
520 return sink, finish
521}
522
523func runJSONMode(ctx context.Context, args Args, version string) error {
524 if args.NoYolo {
525 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
526 }
527 r, err := Resolve(args, true)
528 if err != nil {
529 return err
530 }
531 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
532 defer stopExt()
533
534 ag := r.NewAgent()
535 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
536 sess, _ := openOrCreateSession(args, r, ag, version)
537 defer sess.Close()
538
539 piped, _ := readAllStdin()
540 prompt := combinePromptInput(piped, args.Prompt)
541 if prompt == "" {
542 return fmt.Errorf("json mode requires a prompt (arg or stdin)")
543 }
544
545 start := len(ag.Messages())
546 enc := json.NewEncoder(os.Stdout)
547 preSink := func(ev core.AgentEvent) {
548 _ = enc.Encode(modes.EventToJSON(ev))
549 }
550 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
551 _ = enc.Encode(map[string]any{"type": "error", "message": err.Error()})
552 return err
553 }
554 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
555 err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
556 WriteNewTranscript(ag, sess, start)
557 return err
558}
559
560// runZotfileStartupPre runs entry.pre before the main non-interactive prompt.
561// "!command" values execute via BashTool; other values are sent as an agent turn.
562// shellOut receives live shell chunks (typically os.Stderr); sink receives
563// agent events for plain-text pre (stream mode wires a live text sink).
564func runZotfileStartupPre(ctx context.Context, pre, cwd string, sandbox *tools.Sandbox, ag *core.Agent, sink func(core.AgentEvent), shellOut io.Writer) error {
565 pre = strings.TrimSpace(pre)
566 if pre == "" {
567 return nil
568 }
569 if cmd, ok := modes.ShellEscapeCommand(pre); ok {
570 raw, err := json.Marshal(map[string]any{"command": cmd})
571 if err != nil {
572 return err
573 }
574 if shellOut != nil {
575 fmt.Fprintf(shellOut, "$ %s\n", cmd)
576 if f, ok := shellOut.(interface{ Sync() error }); ok {
577 _ = f.Sync()
578 }
579 }
580 progress := func(chunk string) {
581 if shellOut == nil || chunk == "" {
582 return
583 }
584 fmt.Fprint(shellOut, chunk)
585 if f, ok := shellOut.(interface{ Sync() error }); ok {
586 _ = f.Sync()
587 }
588 }
589 bash := &tools.BashTool{CWD: cwd, Sandbox: sandbox}
590 res, err := bash.Execute(ctx, raw, progress)
591 if err != nil {
592 return fmt.Errorf("zotfile entry.pre: %w", err)
593 }
594 if res.IsError {
595 var sb strings.Builder
596 for _, c := range res.Content {
597 if tb, ok := c.(provider.TextBlock); ok {
598 sb.WriteString(tb.Text)
599 }
600 }
601 msg := strings.TrimSpace(sb.String())
602 if msg == "" {
603 msg = "command failed"
604 }
605 return fmt.Errorf("zotfile entry.pre: %s", msg)
606 }
607 return nil
608 }
609 if ag == nil {
610 return fmt.Errorf("zotfile entry.pre requires an agent for non-shell prompts")
611 }
612 if sink == nil {
613 sink = func(core.AgentEvent) {}
614 }
615 return ag.Prompt(ctx, pre, nil, sink)
616}
617
618// refreshAgentToolsAndPrompt re-resolves tools (including rediscovered
619// skills and currently loaded extension tools) and updates the live
620// agent's registry and system prompt. Used after /reload-ext and after
621// zotfile entry.pre installs new skills or extensions.
622// mutateRegistry, if non-nil, can inject session-specific tools (e.g. swarm_spawn).
623func refreshAgentToolsAndPrompt(args Args, sharedSandbox *tools.Sandbox, extToolAdapter ExtensionToolSource, ag *core.Agent, mutateRegistry func(core.Registry) core.Registry) {
624 if ag == nil {
625 return
626 }
627 resolved, err := Resolve(args, true)
628 if err != nil {
629 return
630 }
631 if sharedSandbox != nil {
632 resolved.UseSandbox(sharedSandbox)
633 }
634 if extToolAdapter != nil {
635 resolved.MergeExtensionTools(extToolAdapter)
636 }
637 reg := resolved.ToolRegistry
638 if mutateRegistry != nil {
639 reg = mutateRegistry(reg)
640 }
641 ag.SetTools(reg)
642 ag.SetSystem(resolved.SystemPrompt)
643}
644
645// reloadResourcesAfterStartupPre reloads extensions (if any) and
646// refreshes the agent tool registry + system prompt so skills/extensions
647// installed by entry.pre are visible to the following turn.
648func reloadResourcesAfterStartupPre(ctx context.Context, args Args, extMgr *extensions.Manager, sharedSandbox *tools.Sandbox, ag *core.Agent) {
649 if strings.TrimSpace(args.StartupPre) == "" || ag == nil {
650 return
651 }
652 adapter := &extToolAdapter{mgr: extMgr}
653 if extMgr != nil {
654 _ = extMgr.Reload(ctx, 2*time.Second)
655 }
656 refreshAgentToolsAndPrompt(args, sharedSandbox, adapter, ag, nil)
657}
658
659// ---- interactive mode: opens the TUI even without credentials ----
660
661func runInteractive(ctx context.Context, args Args, version string) error {
662 // Resolve WITHOUT requiring credentials.
663 r, err := Resolve(args, false)
664 if err != nil {
665 return err
666 }
667
668 authStore := AuthStoreFor()
669 mgr := auth.NewManager(authStore)
670 defer mgr.Close()
671
672 // Keep the sandbox pointer stable across agent rebuilds (login / model
673 // switch). The Interactive UI toggles the lock via this pointer, and
674 // rebuilt tool instances must share the same one so the lock sticks.
675 sharedSandbox := r.Sandbox
676
677 // Build the extension manager BEFORE the agent so we can fold
678 // extension-defined tools into the registry. Forward-declare iv so
679 // the host hooks adapter can dereference it after construction.
680 var iv *modes.Interactive
681 extHooks := &interactiveExtHooks{ivPtr: &iv}
682 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
683 startupExtensionErrors := make([]string, 0, len(r.SkillDiagnostics))
684 for _, diagnostic := range r.SkillDiagnostics {
685 startupExtensionErrors = append(startupExtensionErrors, "skill discovery: "+diagnostic)
686 }
687 // --ext paths first so they win against installed extensions of
688 // the same name (loadOne's first-write-wins semantics).
689 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
690 startupExtensionErrors = append(startupExtensionErrors, e.Error())
691 }
692 // --no-ext skips the global + project-local discovery scan;
693 // explicit --ext paths above are still honoured so you can run
694 // "only this extension" with --no-ext --ext ./x.
695 if !args.NoExt {
696 for _, e := range extMgr.Discover(ctx) {
697 startupExtensionErrors = append(startupExtensionErrors, e.Error())
698 }
699 }
700 // Wait briefly for extensions to flush their initial register_tool
701 // frames before we build the agent's tool registry. Half a second
702 // is plenty for any extension that's actually well-behaved; ones
703 // that don't send a ready frame eat the full grace and proceed.
704 // 3s is the per-extension grace period for the ready frame.
705 // Native binaries are instant; runtimes like `npx tsx` take ~1.5s
706 // from cold cache. The wait is tight only for extensions that
707 // haven't sent ready by then; ones that signalled earlier release
708 // the wait immediately.
709 extMgr.WaitForReady(3 * time.Second)
710 defer extMgr.Stop(2 * time.Second)
711
712 extToolAdapter := &extToolAdapter{mgr: extMgr}
713 r.MergeExtensionTools(extToolAdapter)
714
715 // Build the swarm supervisor BEFORE the agent so the auto-swarm
716 // tool can reference it during tool-registry construction. State
717 // lives under ZotHome/swarm so per-agent meta/events survive
718 // restarts; the user can hunt orphaned agents down with
719 // `git worktree list` if anything misbehaves.
720 //
721 // swarmMgr is also captured by loadSession / changeCWD closures
722 // further down the function, which is why we keep the variable
723 // in this outer scope rather than scoping it tighter.
724 var swarmMgr *swarm.Swarm
725 swarmMgr = swarm.New(swarm.Config{
726 Root: filepath.Join(ZotHome(), "swarm"),
727 RepoRoot: r.CWD,
728 OnLifecycle: func(e swarm.LifecycleEvent) { emitSwarmLifecycle(extMgr, e) },
729 ResolveCredential: func(ctx context.Context, providerID string) (swarm.Credential, error) {
730 if providerID == "ollama" {
731 return swarm.Credential{Value: "ollama", Method: "apikey"}, nil
732 }
733 credential, method, accountID, err := ResolveCredentialFullContext(ctx, providerID, "")
734 if err != nil {
735 // Providers backed only by a local endpoint do not need a key.
736 // Leave stdin untouched and let the child resolve that endpoint.
737 if !CredentialAvailable(providerID) {
738 return swarm.Credential{}, nil
739 }
740 return swarm.Credential{}, err
741 }
742 return swarm.Credential{Value: credential, Method: method, AccountID: accountID}, nil
743 },
744 })
745 // Pull any previously-spawned agents off disk so the dashboard
746 // shows them as detached and the user can resume / remove them.
747 _, _ = swarmMgr.Reload()
748
749 // onSpawnedSwarm is the OnSpawned callback the swarm_spawn tool
750 // fires after every successful spawn. It hands the agent off to
751 // the running Interactive so the watcher can flush a summary back
752 // into chat when all sub-agents finish. Reads `iv` lazily because
753 // the Interactive is constructed after the agent.
754 onSpawnedSwarm := func(a *swarm.Agent, task string) {
755 if iv != nil {
756 iv.TrackSwarmAgent(a, task)
757 }
758 }
759
760 // Inject the swarm_spawn auto-swarm tool only when /settings ->
761 // auto-swarm is currently enabled. Registering it unconditionally
762 // leaves the model trying to call it (and getting a polite error)
763 // even when the user has switched the feature off. The /settings
764 // toggle live-mutates the running agent's registry separately so
765 // flipping the flag mid-session takes effect on the next turn.
766 injectSwarmSpawn := func(reg core.Registry) core.Registry {
767 if reg == nil {
768 return reg
769 }
770 if !AutoSwarmEnabled() {
771 return reg
772 }
773 reg["swarm_spawn"] = &tools.SwarmSpawnTool{
774 Swarm: swarmMgr,
775 Enabled: AutoSwarmEnabled,
776 DefaultModel: func() string { return r.Model },
777 DefaultProvider: func() string { return r.Provider },
778 OnSpawned: onSpawnedSwarm,
779 }
780 return reg
781 }
782 injectSwarmSpawn(r.ToolRegistry)
783
784 // Confirmation gate: when --no-yolo is on, the agent must ask
785 // the user before every tool call. In interactive mode the TUI
786 // provides the Confirmer; in print/json/rpc modes there's no
787 // way to prompt, so the gate is constructed with a nil inner
788 // which auto-refuses every call with a helpful reason.
789 var confirmGate *core.ConfirmGate
790 if args.NoYolo {
791 confirmGate = core.NewConfirmGate(nil) // set below for interactive
792 }
793
794 // Capture current args in a closure so BuildAgent can re-resolve
795 // after a successful login (picks up the newly stored credential).
796 wireAgentExt := func(resolved Resolved) *core.Agent {
797 a := resolved.NewAgent()
798 wireBeforeAgentStart(a, extMgr, resolved.Provider)
799 a.BeforeToolExecuteContext = func(ctx context.Context, call provider.ToolCallBlock) (bool, string, json.RawMessage) {
800 // Guards run before confirmation because they may rewrite the
801 // arguments. The user must approve the effective call that will
802 // actually execute, not the model's original arguments.
803 r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
804 if r.Block {
805 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: r.Reason})
806 return false, r.Reason, r.ModifiedArgs
807 }
808 effectiveArgs := call.Arguments
809 if len(r.ModifiedArgs) > 0 && json.Valid(r.ModifiedArgs) {
810 effectiveArgs = r.ModifiedArgs
811 }
812 if confirmGate != nil {
813 var content strings.Builder
814 if tool, err := a.Tools.Get(call.Name); err == nil {
815 if previewer, ok := tool.(core.ToolPreviewer); ok {
816 preview, err := previewer.Preview(ctx, effectiveArgs)
817 if err != nil {
818 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: err.Error()})
819 return false, err.Error(), effectiveArgs
820 }
821 for _, block := range preview.Content {
822 if text, ok := block.(provider.TextBlock); ok {
823 if content.Len() > 0 {
824 content.WriteString("\n")
825 }
826 content.WriteString(text.Text)
827 }
828 }
829 }
830 }
831 decision := confirmGate.DecideToolCall(core.ToolCallConfirmation{
832 ID: call.ID,
833 Name: call.Name,
834 Summary: core.BuildPreview(effectiveArgs, 120),
835 Content: content.String(),
836 })
837 emitPermissionDecision(ctx, extMgr, call, decision)
838 if !decision.Allow {
839 return false, decision.Reason, effectiveArgs
840 }
841 } else {
842 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Allow: true, Source: "yolo"})
843 }
844 return true, "", r.ModifiedArgs
845 }
846 a.BeforeTurn = func(step int) (bool, string) {
847 r := extMgr.InterceptTurnStart(ctx, step)
848 return !r.Block, r.Reason
849 }
850 a.BeforeAssistantMessage = func(text string) (bool, string, string) {
851 r := extMgr.InterceptAssistantMessage(ctx, text)
852 if r.Block {
853 return false, r.Reason, ""
854 }
855 return true, "", r.ReplaceText
856 }
857 wireLifecycleEvents(a, extMgr)
858 return a
859 }
860
861 buildAgent := func() (*core.Agent, string, string, error) {
862 resolved, err := Resolve(args, true)
863 if err != nil {
864 return nil, "", "", err
865 }
866 resolved.UseSandbox(sharedSandbox)
867 resolved.MergeExtensionTools(extToolAdapter)
868 injectSwarmSpawn(resolved.ToolRegistry)
869 return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
870 }
871
872 // Rebuild agent with an explicit provider/model override.
873 buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
874 next := args
875 if providerOverride != "" {
876 next.Provider = providerOverride
877 }
878 if modelOverride != "" {
879 next.Model = modelOverride
880 }
881 resolved, err := Resolve(next, true)
882 if err != nil {
883 return nil, "", "", err
884 }
885 resolved.UseSandbox(sharedSandbox)
886 resolved.MergeExtensionTools(extToolAdapter)
887 injectSwarmSpawn(resolved.ToolRegistry)
888 return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
889 }
890
891 // Rebuild agent for the rescue picker after a recoverable failure.
892 // Unlike buildAgentFor, this drops launch-time --api-key and
893 // --base-url overrides because those are typically the cause of the
894 // rescue (a bad key, a typo'd base URL, or a corporate gateway that
895 // only the originally-picked provider needed). Re-resolving without
896 // them lets the rescue retry use env vars / auth.json / provider
897 // defaults the way zot would have without the overrides.
898 buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
899 next := args
900 next.APIKey = ""
901 next.BaseURL = ""
902 if providerOverride != "" {
903 next.Provider = providerOverride
904 }
905 if modelOverride != "" {
906 next.Model = modelOverride
907 }
908 resolved, err := Resolve(next, true)
909 if err != nil {
910 return nil, "", "", err
911 }
912 resolved.UseSandbox(sharedSandbox)
913 resolved.MergeExtensionTools(extToolAdapter)
914 injectSwarmSpawn(resolved.ToolRegistry)
915 return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
916 }
917
918 var ag *core.Agent
919 if r.HasCredential() {
920 ag = wireAgentExt(r)
921 }
922
923 // /reload-ext callback: after the manager has respawned every
924 // extension, re-resolve the tool registry (built-ins + freshly-
925 // registered extension tools) and swap it onto the current
926 // agent in-place. The current agent may have been replaced by a
927 // /model swap since spawn, so re-read the live `ag` on each
928 // invocation.
929 extMgr.SetOnReload(func() {
930 current := liveInteractiveAgent(iv, ag)
931 if current == nil {
932 return
933 }
934 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
935 })
936
937 var sess *core.Session
938 var sessBaselineMsgs int // messages already on disk when current session opened
939 // persistMu guards sess + sessBaselineMsgs against concurrent access
940 // from the agent loop's per-message persistence hook (runs on the
941 // agent goroutine) and the TUI's session swap / flush callbacks
942 // (run on the TUI goroutine). Without this, a /sessions swap that
943 // races with a finishing turn could double-write or lose messages.
944 var persistMu sync.Mutex
945 if !args.NoSess && ag != nil {
946 sess, _ = openOrCreateSession(args, r, ag, version)
947 if ag != nil {
948 sessBaselineMsgs = len(ag.Messages())
949 }
950 }
951 startExtensionSession(extMgr, ag, r.CWD, "")
952 defer func() {
953 persistMu.Lock()
954 defer persistMu.Unlock()
955 if sess != nil {
956 sess.Close()
957 }
958 }()
959
960 // persistMessage is the per-message hook bound to the agent. It
961 // appends each new transcript message to the live session as soon
962 // as it lands, so a kill / closed terminal / OS crash costs at
963 // most the in-flight turn instead of the whole session. The
964 // baseline counter advances in lock-step so the exit-time flush
965 // doesn't double-write rows already on disk.
966 persistMessage := func(m provider.Message) {
967 persistMu.Lock()
968 defer persistMu.Unlock()
969 if sess == nil {
970 return
971 }
972 if err := sess.AppendMessage(m); err == nil {
973 sessBaselineMsgs++
974 }
975 }
976 persistUsage := func(cum provider.Usage) {
977 persistMu.Lock()
978 defer persistMu.Unlock()
979 if sess == nil {
980 return
981 }
982 _ = sess.AppendUsage(cum, cum)
983 }
984 persistCompaction := func(messages []provider.Message) {
985 persistMu.Lock()
986 defer persistMu.Unlock()
987 if sess == nil {
988 return
989 }
990 if err := sess.AppendCompaction(messages); err == nil {
991 sessBaselineMsgs = len(messages)
992 }
993 }
994 wireAgentPersist := func(a *core.Agent) *core.Agent {
995 if a == nil {
996 return a
997 }
998 a.OnMessageAppended = persistMessage
999 a.OnUsage = persistUsage
1000 a.OnTranscriptCompacted = persistCompaction
1001 return a
1002 }
1003 wireAgentPersist(ag)
1004
1005 // Re-wrap the build closures so any agent constructed by the TUI
1006 // (login, /model swap to a different provider) also gets the
1007 // persistence hooks. Without this, switching provider would
1008 // silently revert to the old in-memory-only behaviour.
1009 bindLiveAgentSession := func(a *core.Agent) {
1010 persistMu.Lock()
1011 s := sess
1012 persistMu.Unlock()
1013 bindAgentSession(a, s)
1014 }
1015 baseBuildAgent := buildAgent
1016 buildAgent = func() (*core.Agent, string, string, error) {
1017 a, p, m, err := baseBuildAgent()
1018 a = wireAgentPersist(a)
1019 bindLiveAgentSession(a)
1020 return a, p, m, err
1021 }
1022 baseBuildAgentFor := buildAgentFor
1023 buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1024 a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
1025 a = wireAgentPersist(a)
1026 bindLiveAgentSession(a)
1027 return a, p, m, err
1028 }
1029 baseBuildAgentForRescue := buildAgentForRescue
1030 buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1031 a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
1032 a = wireAgentPersist(a)
1033 bindLiveAgentSession(a)
1034 return a, p, m, err
1035 }
1036
1037 // loadSession replaces the current session with the one at path and
1038 // hands its messages to the agent. Used by the /sessions picker.
1039 loadSession := func(path string) error {
1040 currentAg := liveInteractiveAgent(iv, ag)
1041 if currentAg == nil {
1042 return fmt.Errorf("no agent running; log in first")
1043 }
1044 newSess, msgs, err := core.OpenSession(path)
1045 if err != nil {
1046 return err
1047 }
1048 fullMsgCount := len(msgs)
1049 msgs = trimMessagesForResume(msgs, 100)
1050 persistMu.Lock()
1051 // Flush any unsaved messages to the old session before swapping.
1052 // Per-message persistence keeps sessBaselineMsgs current, so
1053 // this is a defensive no-op in the common case; it still
1054 // matters for the rare race where a turn just finished and
1055 // hadn't fired its hook yet.
1056 if sess != nil {
1057 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1058 _ = sess.Close()
1059 }
1060 sess = newSess
1061 currentAg.SetMessages(msgs)
1062 bindAgentSession(currentAg, sess)
1063 startExtensionSession(extMgr, currentAg, r.CWD, "session_switch")
1064 if cum, last, uerr := core.SessionUsageDetail(path); uerr == nil {
1065 currentAg.SeedCost(cum)
1066 currentAg.SeedLastTurnUsage(last)
1067 }
1068 // The live agent only receives a compact resume window, but
1069 // the session file remains intact. Keep the persistence
1070 // baseline at the original on-disk message count so future
1071 // turns append after the full session instead of duplicating
1072 // the hydrated tail.
1073 sessBaselineMsgs = fullMsgCount
1074 persistMu.Unlock()
1075 // Re-scope the swarm dashboard to the new session so /swarm
1076 // only shows agents this session spawned. swarmMgr may be nil
1077 // here if we haven't reached the construction site yet (it
1078 // shouldn't be, since the interactive loop is what triggers
1079 // loadSession, but the nil check is cheap insurance).
1080 if swarmMgr != nil && newSess != nil {
1081 swarmMgr.SetActiveSession(newSess.ID)
1082 }
1083 return nil
1084 }
1085
1086 // changeCWD switches the running session to a new working directory.
1087 // Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
1088 // /cd slash command (which itself is only fired by the workspaces
1089 // extension's panel-key Enter handler today; the user can type /cd
1090 // directly but it's not in autocomplete / help / the README).
1091 //
1092 // Steps, in order:
1093 // 1. resolve + validate the new path (~ expansion, abs/rel)
1094 // 2. close the current session, flushing pending messages
1095 // 3. mutate captured args.CWD + r.CWD so future buildAgent
1096 // calls bind to the new cwd
1097 // 4. re-root the shared sandbox («·«) so /jail follows the
1098 // session into the new cwd instead of widening or silently
1099 // dropping
1100 // 5. rebuild the agent via buildAgent() so tools, AGENTS.md
1101 // addendum, system prompt, sessions dir all bind correctly
1102 // 6. open a fresh session in the new cwd's bucket
1103 // 7. push the new state into the running Interactive
1104 // 8. re-scope the swarm dashboard to the freshly-opened session
1105 //
1106 // The /jail state is preserved verbatim: if the sandbox was locked
1107 // to the old cwd, it stays locked, just re-pointed at the new one.
1108 changeCWD := func(path string) error {
1109 if path == "" {
1110 return fmt.Errorf("empty path")
1111 }
1112 // ~ expansion.
1113 if path == "~" || strings.HasPrefix(path, "~/") {
1114 home, herr := os.UserHomeDir()
1115 if herr != nil || home == "" {
1116 return fmt.Errorf("cannot expand ~: %v", herr)
1117 }
1118 if path == "~" {
1119 path = home
1120 } else {
1121 path = filepath.Join(home, path[2:])
1122 }
1123 }
1124 if !filepath.IsAbs(path) {
1125 path = filepath.Join(args.CWD, path)
1126 }
1127 absPath, err := filepath.Abs(path)
1128 if err != nil {
1129 return err
1130 }
1131 info, err := os.Stat(absPath)
1132 if err != nil {
1133 return err
1134 }
1135 if !info.IsDir() {
1136 return fmt.Errorf("not a directory: %s", absPath)
1137 }
1138
1139 currentAg := ag
1140 if currentAg == nil {
1141 return fmt.Errorf("no agent running; log in first")
1142 }
1143
1144 // Close the current session before we drop the reference.
1145 // Per-message persistence keeps it current already; this is
1146 // a defensive flush + final fsync via Close.
1147 persistMu.Lock()
1148 if sess != nil {
1149 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1150 _ = sess.Close()
1151 sess = nil
1152 }
1153 sessBaselineMsgs = 0
1154 persistMu.Unlock()
1155 extMgr.EndSession("cwd_change")
1156
1157 // Mutate captured state so subsequent agent rebuilds and
1158 // session opens see the new cwd.
1159 wasJailed := sharedSandbox != nil && sharedSandbox.Locked()
1160 args.CWD = absPath
1161 r.CWD = absPath
1162 if args.PermissionSet != nil {
1163 expanded := args.PermissionSet.Expand(absPath, args.AgentDataDir)
1164 args.PermissionSet = &expanded
1165 }
1166 if sharedSandbox != nil {
1167 sharedSandbox.Root = absPath
1168 if wasJailed {
1169 sharedSandbox.Lock()
1170 } else {
1171 sharedSandbox.Unlock()
1172 }
1173 }
1174
1175 // Rebuild the agent so tools / AGENTS.md / system prompt
1176 // re-bind to the new cwd. buildAgent() reads from args + r.
1177 newAg, newProvider, newModel, berr := buildAgent()
1178 if berr != nil {
1179 return fmt.Errorf("rebuild agent: %v", berr)
1180 }
1181 ag = newAg
1182
1183 // Fresh session in the new cwd's bucket. We bypass
1184 // openOrCreateSession's --continue / --resume branches
1185 // because /cd's semantics are "start fresh here", matching
1186 // what relaunching `zot --cwd <path>` would do today.
1187 if !args.NoSess {
1188 newRoot := agentSessionsRoot(ZotHome(), args)
1189 core.PruneEmptySessions(newRoot, absPath)
1190 newSess, serr := core.NewSession(newRoot, absPath, newProvider, newModel, version)
1191 if serr != nil {
1192 return fmt.Errorf("open session in %s: %v", absPath, serr)
1193 }
1194 persistMu.Lock()
1195 sess = newSess
1196 sessBaselineMsgs = 0
1197 persistMu.Unlock()
1198 bindAgentSession(newAg, newSess)
1199 }
1200
1201 startExtensionSession(extMgr, newAg, absPath, "cwd_change")
1202
1203 // Push the new state into the running Interactive.
1204 if iv != nil {
1205 startupPaths := instructionContextPaths(loadAgentsContext(absPath, ZotHome()))
1206 iv.ApplyChangedCWDWithStartupContext(newAg, newProvider, newModel, absPath, startupPaths)
1207 }
1208
1209 // Re-scope the swarm dashboard to the new session.
1210 if swarmMgr != nil {
1211 sessionID, _ := extMgr.SessionContext()
1212 swarmMgr.SetActiveSession(sessionID)
1213 }
1214 return nil
1215 }
1216
1217 term := tui.NewProcTerm()
1218
1219 // Kick off the async update check so the banner can appear when the
1220 // http response eventually arrives (usually <1s on cached DNS). Map
1221 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
1222 updateCh := make(chan modes.UpdateInfo, 1)
1223 go func() {
1224 defer close(updateCh)
1225 src := <-CheckForUpdateAsync(ZotHome(), version)
1226 updateCh <- modes.UpdateInfo{
1227 Current: src.Current,
1228 Latest: src.Latest,
1229 Available: src.Available,
1230 URL: src.URL,
1231 }
1232 }()
1233
1234 // Changelog: when the running version differs from the last
1235 // version whose release notes the user dismissed, fetch the
1236 // release body from GitHub and have the TUI show it once. On
1237 // first-ever launch (no prior LastChangelogShown), seed the
1238 // stored version silently — don't dump release notes at someone
1239 // who just installed.
1240 changelogCh := make(chan modes.ChangelogPayload, 1)
1241 go func() {
1242 defer close(changelogCh)
1243 cfg, _ := LoadConfig()
1244 if cfg.LastChangelogShown == "" {
1245 SeedChangelogVersion(version)
1246 return
1247 }
1248 if !ShouldShowChangelog(version, cfg) {
1249 return
1250 }
1251 info := <-FetchChangelogAsync(version)
1252 if info.Body == "" {
1253 return
1254 }
1255 // For dev builds (0.0.0), skip if the latest release was
1256 // already shown (stored by the dismiss callback).
1257 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
1258 return
1259 }
1260 changelogCh <- modes.ChangelogPayload{
1261 Version: info.Version,
1262 Body: info.Body,
1263 URL: info.URL,
1264 }
1265 }()
1266
1267 initialCfg, _ := LoadConfig()
1268 quickModelShortcuts := make([]modes.QuickModelShortcut, len(initialCfg.QuickModelShortcuts))
1269 for idx, s := range initialCfg.QuickModelShortcuts {
1270 quickModelShortcuts[idx] = modes.QuickModelShortcut{Provider: s.Provider, Model: s.Model}
1271 }
1272 theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
1273 if themeErr != nil {
1274 fmt.Fprintln(os.Stderr, "theme load:", themeErr)
1275 if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
1276 initialCfg.Theme = ""
1277 _ = SaveConfig(initialCfg)
1278 }
1279 }
1280
1281 // swarmMgr was constructed and reloaded earlier (before the agent
1282 // build, so the auto-swarm tool could capture it). Here we just
1283 // scope the dashboard to the active host session so /swarm only
1284 // shows agents this session spawned (and any pre-upgrade unscoped
1285 // agents — see SnapshotAll docs). Updated again whenever the
1286 // user swaps sessions via loadSession below.
1287 sessionID, _ := extMgr.SessionContext()
1288 swarmMgr.SetActiveSession(sessionID)
1289 // Best-effort shutdown on interactive exit: stop all running
1290 // agents so they don't outlive their parent zot.
1291 defer func() {
1292 shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
1293 defer cancel()
1294 swarmMgr.Shutdown(shutdownCtx)
1295 }()
1296
1297 var startupSkills []*skills.Skill
1298 if r.SkillTool != nil {
1299 startupSkills = r.SkillTool.Skills()
1300 }
1301
1302 iv = modes.NewInteractive(modes.InteractiveConfig{
1303 Terminal: term,
1304 Theme: theme,
1305 InlineImagesEnabled: initialCfg.InlineImagesEnabled,
1306 AutoSwarmEnabled: initialCfg.AutoSwarmEnabled,
1307 AutoCompactThreshold: initialCfg.AutoCompactThreshold,
1308 JailByDefault: initialCfg.JailByDefault,
1309 PowerShellEnabled: initialCfg.PowerShellEnabled,
1310 ToolSelectionExplicit: len(args.Tools) > 0,
1311 OpenRouterServerToolsEnabled: initialCfg.OpenRouterServerToolsEnabled,
1312 OpenRouterServerToolCallLimit: initialCfg.OpenRouterServerToolCallLimit,
1313 NoTools: args.NoTools,
1314 QuickModelShortcuts: quickModelShortcuts,
1315 RecursiveFileSuggest: initialCfg.RecursiveFileSuggest,
1316 RespectGitignore: initialCfg.RespectGitignore,
1317 CompactMode: initialCfg.CompactMode,
1318 CollapseToolCall: initialCfg.CollapseToolCall,
1319 TUIInputStyle: initialCfg.TUIInputStyle,
1320 TUIStatusPosition: initialCfg.TUIStatusPosition,
1321 TUIWorkingPosition: initialCfg.TUIWorkingPosition,
1322 ThemeName: initialCfg.Theme,
1323 FlatTools: initialCfg.FlatToolRender(),
1324 CompactUser: initialCfg.CompactUserInput(),
1325 ExtensionThemes: extMgr.ThemeOptions,
1326 AutoSwarmSystemAddendum: AutoSwarmSystemAddendum,
1327 SettingsStore: configSettingsStore{},
1328 Model: r.Model,
1329 Provider: r.Provider,
1330 AuthMethod: r.AuthMethod,
1331 BaseURL: r.BaseURL,
1332 Reasoning: r.Reasoning,
1333 SystemPrompt: r.SystemPrompt,
1334 Tools: r.ToolRegistry,
1335 MaxSteps: r.MaxSteps,
1336 CWD: r.CWD,
1337 StartupAgentName: args.AgentName,
1338 StartupContextPaths: instructionContextPaths(r.ContextFiles),
1339 StartupExtensionNames: startupExtensionNames(extMgr.All()),
1340 StartupExtensionErrors: startupExtensionErrors,
1341 StartupSkillNames: startupSkillNames(startupSkills),
1342 ShowInstructionsAtStartup: initialCfg.ShowInstructionsAtStartup,
1343 ZotHome: ZotHome(),
1344 SessionsRoot: agentSessionsRoot(ZotHome(), args),
1345 Version: version,
1346 UpdateInfoChan: updateCh,
1347 Sandbox: sharedSandbox,
1348 Agent: ag,
1349 InitialInput: args.Prompt,
1350 StartupPre: args.StartupPre,
1351 OnStartupPreDone: func() {
1352 // entry.pre often installs skills/extensions; rediscover them
1353 // before the user starts a model turn.
1354 current := liveInteractiveAgent(iv, ag)
1355 if extMgr != nil {
1356 _ = extMgr.Reload(context.Background(), 2*time.Second)
1357 }
1358 if current != nil {
1359 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
1360 }
1361 },
1362 AuthManager: mgr,
1363 LlamaCPPConfig: ResolveLlamaCPPConfig,
1364 RefreshLlamaCPPModels: RefreshLlamaCPPModels,
1365 BuildAgent: buildAgent,
1366 SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
1367 BuildAgentFor: buildAgentFor,
1368 BuildAgentForRescue: buildAgentForRescue,
1369 LoggedInProviders: func() []string {
1370 var out []string
1371 seen := map[string]bool{}
1372 for _, p := range knownProviders {
1373 if CredentialAvailable(p) && !seen[p] {
1374 out = append(out, p)
1375 seen[p] = true
1376 }
1377 }
1378 // Include custom providers that have credentials stored.
1379 for p := range provider.CustomProviders() {
1380 if CredentialAvailable(p) && !seen[p] {
1381 out = append(out, p)
1382 seen[p] = true
1383 }
1384 }
1385 // Ollama models are always available (no auth needed).
1386 if !seen["ollama"] {
1387 out = append(out, "ollama")
1388 }
1389 return out
1390 },
1391 LoadSession: loadSession,
1392 ChangeCWD: changeCWD,
1393 CurrentSessionPath: func() string {
1394 if sess == nil {
1395 return ""
1396 }
1397 return sess.Path
1398 },
1399 FlushSession: func() {
1400 // Append any not-yet-persisted agent messages to the
1401 // current session file, then advance the baseline so
1402 // the final WriteNewTranscript at exit doesn't write
1403 // duplicates. Per-message persistence keeps the on-
1404 // disk file current already, so this is mostly a
1405 // defensive flush — still needed for /session export
1406 // to guarantee the exported bytes include the very
1407 // last in-flight turn.
1408 currentAg := iv.Agent()
1409 if currentAg == nil {
1410 return
1411 }
1412 persistMu.Lock()
1413 defer persistMu.Unlock()
1414 if sess == nil {
1415 return
1416 }
1417 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1418 sessBaselineMsgs = len(currentAg.Messages())
1419 },
1420 Extensions: extMgr,
1421 Swarm: swarmMgr,
1422 ChangelogChan: changelogCh,
1423 OnChangelogDismiss: func() {
1424 // For dev builds (0.0.0) store the actual release version
1425 // so the same changelog doesn't show again next launch.
1426 // For real builds, store the binary version.
1427 v := version
1428 if v == "0.0.0" {
1429 if iv != nil && iv.ChangelogVersion() != "" {
1430 v = iv.ChangelogVersion()
1431 }
1432 }
1433 _ = MarkChangelogShown(v)
1434 },
1435 SkillSnapshot: func() []*skills.Skill {
1436 if args.NoSkill {
1437 // --no-skill: nothing for the picker to show.
1438 return nil
1439 }
1440 // Re-discover so the picker reflects edits made during
1441 // the session. Cheap; SKILL.md files are small. Filter
1442 // out built-in skills — they're hidden from user-facing
1443 // surfaces because they're implementation detail; the
1444 // model still sees them through the system-prompt
1445 // manifest and the skill tool.
1446 userHome, _ := os.UserHomeDir()
1447 var sources []skills.Source
1448 if args.WithSkills {
1449 sources = append(sources, skills.SearchSources(ZotHome(), r.CWD, userHome)...)
1450 }
1451 if !args.NoExt || len(args.Exts) > 0 {
1452 extSources, _ := extensions.PlanSkillSources(ZotHome(), r.CWD, args.Exts, !args.NoExt)
1453 sources = append(extSources, sources...)
1454 }
1455 list, _ := skills.DiscoverSources(sources, true)
1456 return skills.VisibleSkills(list)
1457 },
1458 NoYolo: args.NoYolo,
1459 ConfirmGate: confirmGate,
1460 PersistModel: func(providerName, model string) {
1461 // Update config.json so next launch uses the same pick.
1462 cfg, _ := LoadConfig()
1463 cfg.Provider = providerName
1464 cfg.Model = model
1465 _ = SaveConfig(cfg)
1466 // Update the active session's meta so resume picks this up.
1467 if sess != nil {
1468 _ = sess.UpdateModel(providerName, model)
1469 }
1470 },
1471 })
1472
1473 // Bind the interactive TUI as the Confirmer. We deferred this
1474 // until now because the gate is constructed before the TUI
1475 // (the BeforeToolExecute closure captures it). SetConfirmer
1476 // is mutex-guarded on the gate so this is safe.
1477 if confirmGate != nil {
1478 confirmGate.SetConfirmer(&confirmationEventConfirmer{
1479 inner: iv,
1480 emit: extMgr.EmitEvent,
1481 })
1482 }
1483
1484 // Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1485 // (closed terminal window, system shutdown, kill) used to lose
1486 // the entire in-memory transcript because the deferred post-Run
1487 // flush below never ran. Per-message persistence above covers
1488 // most of it; this handler writes any in-flight remainder and
1489 // then exits the process so we don't double-paint over a
1490 // broken terminal that the TUI's restore deferreds can no
1491 // longer fix from a signal context.
1492 //
1493 // SIGINT is intentionally NOT handled here — the TUI consumes
1494 // Ctrl+C as a regular key event for cancel/clear semantics, and
1495 // installing a SIGINT notifier here would swallow it.
1496 sigCh := make(chan os.Signal, 1)
1497 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1498 defer signal.Stop(sigCh)
1499 go func() {
1500 _, ok := <-sigCh
1501 if !ok {
1502 return
1503 }
1504 if finalAg := iv.Agent(); finalAg != nil {
1505 persistMu.Lock()
1506 if sess != nil {
1507 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1508 sessBaselineMsgs = len(finalAg.Messages())
1509 _ = sess.Close()
1510 sess = nil
1511 }
1512 persistMu.Unlock()
1513 }
1514 // Exit cleanly. Re-raising the signal would skip os.Exit's
1515 // at-exit hooks; explicit exit is fine because we've already
1516 // flushed the only at-risk state (the session file).
1517 os.Exit(0)
1518 }()
1519
1520 runErr := iv.Run(ctx)
1521
1522 // Flush final transcript to session (only if we had / ended up with an agent).
1523 if finalAg := iv.Agent(); finalAg != nil {
1524 persistMu.Lock()
1525 if sess != nil {
1526 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1527 sessBaselineMsgs = len(finalAg.Messages())
1528 }
1529 persistMu.Unlock()
1530 }
1531 return runErr
1532}
1533
1534func agentSessionsRoot(root string, args Args) string {
1535 if args.AgentName == "" {
1536 return root
1537 }
1538 return filepath.Join(root, "sessions", "agents", safeAgentName(args.AgentName))
1539}
1540
1541// openOrCreateSession returns a session for the run. sess may be nil
1542// with a nil error if session persistence is disabled. When a session
1543// exists, its id is bound onto ag so providers can sticky-route.
1544func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1545 if args.NoSess {
1546 return nil, nil
1547 }
1548 // Sweep meta-only files left over from older zot versions (and from
1549 // any session that crashed before its first AppendMessage). Cheap;
1550 // reads the first few bytes of each file in the cwd's session dir.
1551 sessionsRoot := agentSessionsRoot(ZotHome(), args)
1552 core.PruneEmptySessions(sessionsRoot, args.CWD)
1553 var (
1554 s *core.Session
1555 msgs []provider.Message
1556 err error
1557 )
1558 switch {
1559 case args.Session != "":
1560 s, msgs, err = core.OpenSession(args.Session)
1561 // The swarm-agent child passes a fixed --session path that
1562 // may not exist yet on first Spawn. Treat ENOENT as "create
1563 // a fresh session AT THIS PATH" so the conversation actually
1564 // gets persisted; without this fallback the swarm child runs
1565 // with sess==nil and every Resume re-starts with no memory
1566 // of the prior turns. Other openers (--continue / --resume /
1567 // the picker) never see ENOENT here because they only choose
1568 // paths that already exist on disk.
1569 if err != nil && errors.Is(err, os.ErrNotExist) {
1570 s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1571 msgs = nil
1572 }
1573 case args.Continue:
1574 latest := core.LatestSession(sessionsRoot, args.CWD)
1575 if latest != "" {
1576 s, msgs, err = core.OpenSession(latest)
1577 }
1578 case args.Resume:
1579 picked, perr := pickSession(sessionsRoot, args.CWD)
1580 if perr != nil {
1581 return nil, perr
1582 }
1583 if picked != "" {
1584 s, msgs, err = core.OpenSession(picked)
1585 }
1586 }
1587 if err != nil {
1588 return nil, err
1589 }
1590 if s == nil {
1591 s, err = core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
1592 if err != nil {
1593 return nil, err
1594 }
1595 } else {
1596 ag.SetMessages(msgs)
1597 if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1598 ag.SeedCost(cum)
1599 ag.SeedLastTurnUsage(last)
1600 }
1601 }
1602 bindAgentSession(ag, s)
1603 return s, nil
1604}
1605
1606func pickSession(root, cwd string) (string, error) {
1607 files := core.ListSessions(root, cwd)
1608 if len(files) == 0 {
1609 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1610 return "", nil
1611 }
1612 for i, f := range files {
1613 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
1614 }
1615 fmt.Fprint(os.Stderr, "pick #: ")
1616 rd := bufio.NewReader(os.Stdin)
1617 line, _ := rd.ReadString('\n')
1618 line = strings.TrimSpace(line)
1619 var n int
1620 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1621 return "", fmt.Errorf("invalid selection")
1622 }
1623 return files[n-1], nil
1624}
1625
1626// WriteNewTranscript appends only messages after index `from` from the
1627// agent's transcript to the session. Used by callers that don't hold
1628// the persistMu (non-interactive print/json modes which run a single
1629// turn under their own goroutine).
1630func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1631 writeNewTranscriptLocked(ag, sess, from)
1632}
1633
1634// bindAgentSession stamps the zot session id onto the agent so providers
1635// that support sticky routing (OpenRouter session_id) can reuse it.
1636// No-op when persistence is disabled.
1637func bindAgentSession(ag *core.Agent, sess *core.Session) {
1638 if ag == nil || sess == nil {
1639 return
1640 }
1641 ag.SessionID = sess.ID
1642}
1643
1644// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1645// suffix marks that interactive callers must hold persistMu when
1646// invoking it so concurrent appends from the agent loop don't race
1647// with this catch-up flush.
1648func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1649 if sess == nil || ag == nil {
1650 return
1651 }
1652 msgs := ag.Messages()
1653 for i := from; i < len(msgs); i++ {
1654 _ = sess.AppendMessage(msgs[i])
1655 }
1656 cum := ag.Cost()
1657 _ = sess.AppendUsage(cum, cum)
1658}
1659
1660func argsForStdin(rawArgs []string, mode os.FileMode) []string {
1661 if mode&os.ModeCharDevice != 0 {
1662 return rawArgs
1663 }
1664 return append([]string{"--print"}, rawArgs...)
1665}
1666
1667func combinePromptInput(stdin, positional string) string {
1668 parts := make([]string, 0, 2)
1669 if stdin = strings.TrimSpace(stdin); stdin != "" {
1670 parts = append(parts, stdin)
1671 }
1672 if positional = strings.TrimSpace(positional); positional != "" {
1673 parts = append(parts, positional)
1674 }
1675 return strings.Join(parts, "\n")
1676}
1677
1678func readAllStdin() (string, error) {
1679 fi, err := os.Stdin.Stat()
1680 if err != nil {
1681 return "", err
1682 }
1683 if (fi.Mode() & os.ModeCharDevice) != 0 {
1684 return "", nil
1685 }
1686 b, err := io.ReadAll(os.Stdin)
1687 return string(b), err
1688}
1689
1690func printModels() {
1691 models := provider.Active()
1692
1693 // Compute column widths from actual data so wide providers (e.g.
1694 // xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1695 // `name` column off-screen. Floors mirror the historical layout so
1696 // short catalogs look the same as before.
1697 provW, idW, srcW := len("provider"), len("model id"), len("source")
1698 for _, m := range models {
1699 if w := len(m.Provider); w > provW {
1700 provW = w
1701 }
1702 if w := len(m.ID); w > idW {
1703 idW = w
1704 }
1705 source := m.Source
1706 if source == "" {
1707 source = "catalog"
1708 }
1709 if m.Speculative {
1710 source = "speculative"
1711 }
1712 if w := len(source); w > srcW {
1713 srcW = w
1714 }
1715 }
1716
1717 header := fmt.Sprintf("%-*s %-*s %8s %8s %s %-*s %s",
1718 provW, "provider",
1719 idW, "model id",
1720 "context", "max-out", "reasoning",
1721 srcW, "source",
1722 "name")
1723 fmt.Println(header)
1724
1725 for _, m := range models {
1726 reason := " "
1727 if m.Reasoning {
1728 reason = "✓"
1729 }
1730 source := m.Source
1731 if source == "" {
1732 source = "catalog"
1733 }
1734 if m.Speculative {
1735 source = "speculative"
1736 }
1737 fmt.Printf("%-*s %-*s %8d %8d %s %-*s %s\n",
1738 provW, m.Provider,
1739 idW, m.ID,
1740 m.ContextWindow, m.MaxOutput,
1741 reason,
1742 srcW, source,
1743 m.DisplayName)
1744 }
1745}