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