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