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