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