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