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, _ := openOrCreateSession(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 started := time.Now()
446 usage, err := modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
447 elapsed := time.Since(started)
448 WriteNewTranscript(ag, sess, start)
449 if err != nil {
450 return err
451 }
452 if args.StatsPath != "" {
453 return writePrintStats(args.StatsPath, r.Provider, r.Model, usage, elapsed)
454 }
455 return nil
456}
457
458func runStreamMode(ctx context.Context, args Args, version string) error {
459 if args.NoYolo {
460 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in stream mode (no interactive prompt available); tools will run without confirmation")
461 }
462 r, err := Resolve(args, true)
463 if err != nil {
464 return err
465 }
466 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
467 defer stopExt()
468
469 ag := r.NewAgent()
470 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
471 sess, _ := openOrCreateSession(args, r, ag, version)
472 defer sess.Close()
473
474 piped, _ := readAllStdin()
475 prompt := combinePromptInput(piped, args.Prompt)
476 if prompt == "" {
477 return fmt.Errorf("stream mode requires a prompt (arg or stdin)")
478 }
479
480 start := len(ag.Messages())
481 preSink, finishPre := newStreamTextSink(os.Stdout)
482 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
483 finishPre()
484 return err
485 }
486 finishPre()
487 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
488 err = modes.RunStream(ctx, ag, prompt, nil, os.Stdout)
489 WriteNewTranscript(ag, sess, start)
490 return err
491}
492
493func newStreamTextSink(out io.Writer) (func(core.AgentEvent), func()) {
494 var streamed, wroteText, lastWasNL bool
495 writeText := func(text string) {
496 if text == "" {
497 return
498 }
499 _, _ = fmt.Fprint(out, text)
500 if syncer, ok := out.(interface{ Sync() error }); ok {
501 _ = syncer.Sync()
502 }
503 wroteText = true
504 lastWasNL = strings.HasSuffix(text, "\n")
505 }
506 sink := func(ev core.AgentEvent) {
507 switch e := ev.(type) {
508 case core.EvAssistantStart:
509 streamed = false
510 case core.EvTextDelta:
511 streamed = true
512 writeText(e.Delta)
513 case core.EvAssistantMessage:
514 if streamed {
515 return
516 }
517 var text strings.Builder
518 for _, content := range e.Message.Content {
519 if block, ok := content.(provider.TextBlock); ok {
520 if text.Len() > 0 {
521 text.WriteString("\n")
522 }
523 text.WriteString(block.Text)
524 }
525 }
526 writeText(text.String())
527 }
528 }
529 finish := func() {
530 if wroteText && !lastWasNL {
531 writeText("\n")
532 }
533 }
534 return sink, finish
535}
536
537func runJSONMode(ctx context.Context, args Args, version string) error {
538 if args.NoYolo {
539 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
540 }
541 r, err := Resolve(args, true)
542 if err != nil {
543 return err
544 }
545 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
546 defer stopExt()
547
548 ag := r.NewAgent()
549 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
550 sess, _ := openOrCreateSession(args, r, ag, version)
551 defer sess.Close()
552
553 piped, _ := readAllStdin()
554 prompt := combinePromptInput(piped, args.Prompt)
555 if prompt == "" {
556 return fmt.Errorf("json mode requires a prompt (arg or stdin)")
557 }
558
559 start := len(ag.Messages())
560 enc := json.NewEncoder(os.Stdout)
561 preSink := func(ev core.AgentEvent) {
562 _ = enc.Encode(modes.EventToJSON(ev))
563 }
564 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
565 _ = enc.Encode(map[string]any{"type": "error", "message": err.Error()})
566 return err
567 }
568 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
569 err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
570 WriteNewTranscript(ag, sess, start)
571 return err
572}
573
574// runZotfileStartupPre runs entry.pre before the main non-interactive prompt.
575// "!command" values execute via BashTool; other values are sent as an agent turn.
576// shellOut receives live shell chunks (typically os.Stderr); sink receives
577// agent events for plain-text pre (stream mode wires a live text sink).
578func runZotfileStartupPre(ctx context.Context, pre, cwd string, sandbox *tools.Sandbox, ag *core.Agent, sink func(core.AgentEvent), shellOut io.Writer) error {
579 pre = strings.TrimSpace(pre)
580 if pre == "" {
581 return nil
582 }
583 if cmd, ok := modes.ShellEscapeCommand(pre); ok {
584 raw, err := json.Marshal(map[string]any{"command": cmd})
585 if err != nil {
586 return err
587 }
588 if shellOut != nil {
589 fmt.Fprintf(shellOut, "$ %s\n", cmd)
590 if f, ok := shellOut.(interface{ Sync() error }); ok {
591 _ = f.Sync()
592 }
593 }
594 progress := func(chunk string) {
595 if shellOut == nil || chunk == "" {
596 return
597 }
598 fmt.Fprint(shellOut, chunk)
599 if f, ok := shellOut.(interface{ Sync() error }); ok {
600 _ = f.Sync()
601 }
602 }
603 bash := &tools.BashTool{CWD: cwd, Sandbox: sandbox}
604 res, err := bash.Execute(ctx, raw, progress)
605 if err != nil {
606 return fmt.Errorf("zotfile entry.pre: %w", err)
607 }
608 if res.IsError {
609 var sb strings.Builder
610 for _, c := range res.Content {
611 if tb, ok := c.(provider.TextBlock); ok {
612 sb.WriteString(tb.Text)
613 }
614 }
615 msg := strings.TrimSpace(sb.String())
616 if msg == "" {
617 msg = "command failed"
618 }
619 return fmt.Errorf("zotfile entry.pre: %s", msg)
620 }
621 return nil
622 }
623 if ag == nil {
624 return fmt.Errorf("zotfile entry.pre requires an agent for non-shell prompts")
625 }
626 if sink == nil {
627 sink = func(core.AgentEvent) {}
628 }
629 return ag.Prompt(ctx, pre, nil, sink)
630}
631
632// refreshAgentToolsAndPrompt re-resolves tools (including rediscovered
633// skills and currently loaded extension tools) and updates the live
634// agent's registry and system prompt. Used after /reload-ext and after
635// zotfile entry.pre installs new skills or extensions.
636// mutateRegistry, if non-nil, can inject session-specific tools (e.g. swarm_spawn).
637func refreshAgentToolsAndPrompt(args Args, sharedSandbox *tools.Sandbox, extToolAdapter ExtensionToolSource, ag *core.Agent, mutateRegistry func(core.Registry) core.Registry) {
638 if ag == nil {
639 return
640 }
641 resolved, err := Resolve(args, true)
642 if err != nil {
643 return
644 }
645 if sharedSandbox != nil {
646 resolved.UseSandbox(sharedSandbox)
647 }
648 if extToolAdapter != nil {
649 resolved.MergeExtensionTools(extToolAdapter)
650 }
651 reg := resolved.ToolRegistry
652 if mutateRegistry != nil {
653 reg = mutateRegistry(reg)
654 }
655 ag.SetTools(reg)
656 ag.SetSystem(resolved.SystemPrompt)
657}
658
659// reloadResourcesAfterStartupPre reloads extensions (if any) and
660// refreshes the agent tool registry + system prompt so skills/extensions
661// installed by entry.pre are visible to the following turn.
662func reloadResourcesAfterStartupPre(ctx context.Context, args Args, extMgr *extensions.Manager, sharedSandbox *tools.Sandbox, ag *core.Agent) {
663 if strings.TrimSpace(args.StartupPre) == "" || ag == nil {
664 return
665 }
666 adapter := &extToolAdapter{mgr: extMgr}
667 if extMgr != nil {
668 _ = extMgr.Reload(ctx, 2*time.Second)
669 }
670 refreshAgentToolsAndPrompt(args, sharedSandbox, adapter, ag, nil)
671}
672
673// ---- interactive mode: opens the TUI even without credentials ----
674
675func runInteractive(ctx context.Context, args Args, version string) error {
676 // Resolve WITHOUT requiring credentials.
677 r, err := Resolve(args, false)
678 if err != nil {
679 return err
680 }
681
682 authStore := AuthStoreFor()
683 mgr := auth.NewManager(authStore)
684 defer mgr.Close()
685
686 // Keep the sandbox pointer stable across agent rebuilds (login / model
687 // switch). The Interactive UI toggles the lock via this pointer, and
688 // rebuilt tool instances must share the same one so the lock sticks.
689 sharedSandbox := r.Sandbox
690
691 // Build the extension manager BEFORE the agent so we can fold
692 // extension-defined tools into the registry. Forward-declare iv so
693 // the host hooks adapter can dereference it after construction.
694 var iv *modes.Interactive
695 extHooks := &interactiveExtHooks{ivPtr: &iv}
696 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
697 startupExtensionErrors := make([]string, 0, len(r.SkillDiagnostics))
698 for _, diagnostic := range r.SkillDiagnostics {
699 startupExtensionErrors = append(startupExtensionErrors, "skill discovery: "+diagnostic)
700 }
701 // --ext paths first so they win against installed extensions of
702 // the same name (loadOne's first-write-wins semantics).
703 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
704 startupExtensionErrors = append(startupExtensionErrors, e.Error())
705 }
706 // --no-ext skips the global + project-local discovery scan;
707 // explicit --ext paths above are still honoured so you can run
708 // "only this extension" with --no-ext --ext ./x.
709 if !args.NoExt {
710 for _, e := range extMgr.Discover(ctx) {
711 startupExtensionErrors = append(startupExtensionErrors, e.Error())
712 }
713 }
714 // Wait briefly for extensions to flush their initial register_tool
715 // frames before we build the agent's tool registry. Half a second
716 // is plenty for any extension that's actually well-behaved; ones
717 // that don't send a ready frame eat the full grace and proceed.
718 // 3s is the per-extension grace period for the ready frame.
719 // Native binaries are instant; runtimes like `npx tsx` take ~1.5s
720 // from cold cache. The wait is tight only for extensions that
721 // haven't sent ready by then; ones that signalled earlier release
722 // the wait immediately.
723 extMgr.WaitForReady(3 * time.Second)
724 defer extMgr.Stop(2 * time.Second)
725
726 extToolAdapter := &extToolAdapter{mgr: extMgr}
727 r.MergeExtensionTools(extToolAdapter)
728
729 // Build the swarm supervisor BEFORE the agent so the auto-swarm
730 // tool can reference it during tool-registry construction. State
731 // lives under ZotHome/swarm so per-agent meta/events survive
732 // restarts; the user can hunt orphaned agents down with
733 // `git worktree list` if anything misbehaves.
734 //
735 // swarmMgr is also captured by loadSession / changeCWD closures
736 // further down the function, which is why we keep the variable
737 // in this outer scope rather than scoping it tighter.
738 var swarmMgr *swarm.Swarm
739 swarmMgr = swarm.New(swarm.Config{
740 Root: filepath.Join(ZotHome(), "swarm"),
741 RepoRoot: r.CWD,
742 OnLifecycle: func(e swarm.LifecycleEvent) { emitSwarmLifecycle(extMgr, e) },
743 ResolveCredential: func(ctx context.Context, providerID string) (swarm.Credential, error) {
744 if providerID == "ollama" {
745 return swarm.Credential{Value: "ollama", Method: "apikey"}, nil
746 }
747 credential, method, accountID, err := ResolveCredentialFullContext(ctx, providerID, "")
748 if err != nil {
749 // Providers backed only by a local endpoint do not need a key.
750 // Leave stdin untouched and let the child resolve that endpoint.
751 if !CredentialAvailable(providerID) {
752 return swarm.Credential{}, nil
753 }
754 return swarm.Credential{}, err
755 }
756 return swarm.Credential{Value: credential, Method: method, AccountID: accountID}, nil
757 },
758 })
759 // Pull any previously-spawned agents off disk so the dashboard
760 // shows them as detached and the user can resume / remove them.
761 _, _ = swarmMgr.Reload()
762
763 // onSpawnedSwarm is the OnSpawned callback the swarm_spawn tool
764 // fires after every successful spawn. It hands the agent off to
765 // the running Interactive so the watcher can flush a summary back
766 // into chat when all sub-agents finish. Reads `iv` lazily because
767 // the Interactive is constructed after the agent.
768 onSpawnedSwarm := func(a *swarm.Agent, task string) {
769 if iv != nil {
770 iv.TrackSwarmAgent(a, task)
771 }
772 }
773
774 // Inject the swarm_spawn auto-swarm tool only when /settings ->
775 // auto-swarm is currently enabled. Registering it unconditionally
776 // leaves the model trying to call it (and getting a polite error)
777 // even when the user has switched the feature off. The /settings
778 // toggle live-mutates the running agent's registry separately so
779 // flipping the flag mid-session takes effect on the next turn.
780 injectSwarmSpawn := func(reg core.Registry) core.Registry {
781 if reg == nil {
782 return reg
783 }
784 if !AutoSwarmEnabled() {
785 return reg
786 }
787 reg["swarm_spawn"] = &tools.SwarmSpawnTool{
788 Swarm: swarmMgr,
789 Enabled: AutoSwarmEnabled,
790 DefaultModel: func() string { return r.Model },
791 DefaultProvider: func() string { return r.Provider },
792 OnSpawned: onSpawnedSwarm,
793 }
794 return reg
795 }
796 injectSwarmSpawn(r.ToolRegistry)
797
798 // Confirmation gate: when --no-yolo is on, the agent must ask
799 // the user before every tool call. In interactive mode the TUI
800 // provides the Confirmer; in print/json/rpc modes there's no
801 // way to prompt, so the gate is constructed with a nil inner
802 // which auto-refuses every call with a helpful reason.
803 var confirmGate *core.ConfirmGate
804 if args.NoYolo {
805 confirmGate = core.NewConfirmGate(nil) // set below for interactive
806 }
807
808 // Capture current args in a closure so BuildAgent can re-resolve
809 // after a successful login (picks up the newly stored credential).
810 wireAgentExt := func(resolved Resolved) *core.Agent {
811 a := resolved.NewAgent()
812 wireBeforeAgentStart(a, extMgr, resolved.Provider)
813 a.BeforeToolExecuteContext = func(ctx context.Context, call provider.ToolCallBlock) (bool, string, json.RawMessage) {
814 // Guards run before confirmation because they may rewrite the
815 // arguments. The user must approve the effective call that will
816 // actually execute, not the model's original arguments.
817 r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
818 if r.Block {
819 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: r.Reason})
820 return false, r.Reason, r.ModifiedArgs
821 }
822 effectiveArgs := call.Arguments
823 if len(r.ModifiedArgs) > 0 && json.Valid(r.ModifiedArgs) {
824 effectiveArgs = r.ModifiedArgs
825 }
826 if confirmGate != nil {
827 var content strings.Builder
828 if tool, err := a.Tools.Get(call.Name); err == nil {
829 if previewer, ok := tool.(core.ToolPreviewer); ok {
830 preview, err := previewer.Preview(ctx, effectiveArgs)
831 if err != nil {
832 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: err.Error()})
833 return false, err.Error(), effectiveArgs
834 }
835 for _, block := range preview.Content {
836 if text, ok := block.(provider.TextBlock); ok {
837 if content.Len() > 0 {
838 content.WriteString("\n")
839 }
840 content.WriteString(text.Text)
841 }
842 }
843 }
844 }
845 decision := confirmGate.DecideToolCall(core.ToolCallConfirmation{
846 ID: call.ID,
847 Name: call.Name,
848 Summary: core.BuildPreview(effectiveArgs, 120),
849 Content: content.String(),
850 })
851 emitPermissionDecision(ctx, extMgr, call, decision)
852 if !decision.Allow {
853 return false, decision.Reason, effectiveArgs
854 }
855 } else {
856 emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Allow: true, Source: "yolo"})
857 }
858 return true, "", r.ModifiedArgs
859 }
860 a.BeforeTurn = func(step int) (bool, string) {
861 r := extMgr.InterceptTurnStart(ctx, step)
862 return !r.Block, r.Reason
863 }
864 a.BeforeAssistantMessage = func(text string) (bool, string, string) {
865 r := extMgr.InterceptAssistantMessage(ctx, text)
866 if r.Block {
867 return false, r.Reason, ""
868 }
869 return true, "", r.ReplaceText
870 }
871 wireLifecycleEvents(a, extMgr)
872 return a
873 }
874
875 buildAgent := func() (*core.Agent, string, string, error) {
876 resolved, err := Resolve(args, true)
877 if err != nil {
878 return nil, "", "", err
879 }
880 resolved.UseSandbox(sharedSandbox)
881 resolved.MergeExtensionTools(extToolAdapter)
882 injectSwarmSpawn(resolved.ToolRegistry)
883 return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
884 }
885
886 // Rebuild agent with an explicit provider/model override.
887 buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
888 next := args
889 if providerOverride != "" {
890 next.Provider = providerOverride
891 }
892 if modelOverride != "" {
893 next.Model = modelOverride
894 }
895 resolved, err := Resolve(next, true)
896 if err != nil {
897 return nil, "", "", err
898 }
899 resolved.UseSandbox(sharedSandbox)
900 resolved.MergeExtensionTools(extToolAdapter)
901 injectSwarmSpawn(resolved.ToolRegistry)
902 return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
903 }
904
905 // Rebuild agent for the rescue picker after a recoverable failure.
906 // Unlike buildAgentFor, this drops launch-time --api-key and
907 // --base-url overrides because those are typically the cause of the
908 // rescue (a bad key, a typo'd base URL, or a corporate gateway that
909 // only the originally-picked provider needed). Re-resolving without
910 // them lets the rescue retry use env vars / auth.json / provider
911 // defaults the way zot would have without the overrides.
912 buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
913 next := args
914 next.APIKey = ""
915 next.BaseURL = ""
916 if providerOverride != "" {
917 next.Provider = providerOverride
918 }
919 if modelOverride != "" {
920 next.Model = modelOverride
921 }
922 resolved, err := Resolve(next, true)
923 if err != nil {
924 return nil, "", "", err
925 }
926 resolved.UseSandbox(sharedSandbox)
927 resolved.MergeExtensionTools(extToolAdapter)
928 injectSwarmSpawn(resolved.ToolRegistry)
929 return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
930 }
931
932 var ag *core.Agent
933 if r.HasCredential() {
934 ag = wireAgentExt(r)
935 }
936
937 // /reload-ext callback: after the manager has respawned every
938 // extension, re-resolve the tool registry (built-ins + freshly-
939 // registered extension tools) and swap it onto the current
940 // agent in-place. The current agent may have been replaced by a
941 // /model swap since spawn, so re-read the live `ag` on each
942 // invocation.
943 extMgr.SetOnReload(func() {
944 current := liveInteractiveAgent(iv, ag)
945 if current == nil {
946 return
947 }
948 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
949 })
950
951 var sess *core.Session
952 var sessBaselineMsgs int // messages already on disk when current session opened
953 // persistMu guards sess + sessBaselineMsgs against concurrent access
954 // from the agent loop's per-message persistence hook (runs on the
955 // agent goroutine) and the TUI's session swap / flush callbacks
956 // (run on the TUI goroutine). Without this, a /sessions swap that
957 // races with a finishing turn could double-write or lose messages.
958 var persistMu sync.Mutex
959 if ag != nil {
960 sess, _ = openOrCreateSession(args, r, ag, version)
961 if ag != nil {
962 sessBaselineMsgs = len(ag.Messages())
963 }
964 }
965 startExtensionSession(extMgr, ag, r.CWD, "")
966 defer func() {
967 persistMu.Lock()
968 defer persistMu.Unlock()
969 if sess != nil {
970 sess.Close()
971 }
972 }()
973
974 // persistMessage is the per-message hook bound to the agent. It
975 // appends each new transcript message to the live session as soon
976 // as it lands, so a kill / closed terminal / OS crash costs at
977 // most the in-flight turn instead of the whole session. The
978 // baseline counter advances in lock-step so the exit-time flush
979 // doesn't double-write rows already on disk.
980 persistMessage := func(m provider.Message) {
981 persistMu.Lock()
982 defer persistMu.Unlock()
983 if sess == nil {
984 return
985 }
986 if err := sess.AppendMessage(m); err == nil {
987 sessBaselineMsgs++
988 }
989 }
990 persistUsage := func(cum provider.Usage) {
991 persistMu.Lock()
992 defer persistMu.Unlock()
993 if sess == nil {
994 return
995 }
996 _ = sess.AppendUsage(cum, cum)
997 }
998 persistCompaction := func(messages []provider.Message) {
999 persistMu.Lock()
1000 defer persistMu.Unlock()
1001 if sess == nil {
1002 return
1003 }
1004 if err := sess.AppendCompaction(messages); err == nil {
1005 sessBaselineMsgs = len(messages)
1006 }
1007 }
1008 wireAgentPersist := func(a *core.Agent) *core.Agent {
1009 if a == nil {
1010 return a
1011 }
1012 a.OnMessageAppended = persistMessage
1013 a.OnUsage = persistUsage
1014 a.OnTranscriptCompacted = persistCompaction
1015 return a
1016 }
1017 wireAgentPersist(ag)
1018
1019 // Re-wrap the build closures so any agent constructed by the TUI
1020 // (login, /model swap to a different provider) also gets the
1021 // persistence hooks. Without this, switching provider would
1022 // silently revert to the old in-memory-only behaviour.
1023 bindLiveAgentSession := func(a *core.Agent) {
1024 persistMu.Lock()
1025 s := sess
1026 persistMu.Unlock()
1027 bindAgentSession(a, s)
1028 }
1029 baseBuildAgent := buildAgent
1030 buildAgent = func() (*core.Agent, string, string, error) {
1031 a, p, m, err := baseBuildAgent()
1032 a = wireAgentPersist(a)
1033 bindLiveAgentSession(a)
1034 return a, p, m, err
1035 }
1036 baseBuildAgentFor := buildAgentFor
1037 buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1038 a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
1039 a = wireAgentPersist(a)
1040 bindLiveAgentSession(a)
1041 return a, p, m, err
1042 }
1043 baseBuildAgentForRescue := buildAgentForRescue
1044 buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1045 a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
1046 a = wireAgentPersist(a)
1047 bindLiveAgentSession(a)
1048 return a, p, m, err
1049 }
1050
1051 // loadSession replaces the current session with the one at path and
1052 // hands its messages to the agent. Used by the /sessions picker.
1053 loadSession := func(path string) error {
1054 currentAg := liveInteractiveAgent(iv, ag)
1055 if currentAg == nil {
1056 return fmt.Errorf("no agent running; log in first")
1057 }
1058 newSess, msgs, err := core.OpenSession(path)
1059 if err != nil {
1060 return err
1061 }
1062 fullMsgCount := len(msgs)
1063 msgs = trimMessagesForResume(msgs, 100)
1064 persistMu.Lock()
1065 // Flush any unsaved messages to the old session before swapping.
1066 // Per-message persistence keeps sessBaselineMsgs current, so
1067 // this is a defensive no-op in the common case; it still
1068 // matters for the rare race where a turn just finished and
1069 // hadn't fired its hook yet.
1070 if sess != nil {
1071 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1072 _ = sess.Close()
1073 }
1074 sess = newSess
1075 currentAg.SetMessages(msgs)
1076 bindAgentSession(currentAg, sess)
1077 setZotSessionEnvironment(r, sess)
1078 startExtensionSession(extMgr, currentAg, r.CWD, "session_switch")
1079 if cum, last, uerr := core.SessionUsageDetail(path); uerr == nil {
1080 currentAg.SeedCost(cum)
1081 currentAg.SeedLastTurnUsage(last)
1082 }
1083 // The live agent only receives a compact resume window, but
1084 // the session file remains intact. Keep the persistence
1085 // baseline at the original on-disk message count so future
1086 // turns append after the full session instead of duplicating
1087 // the hydrated tail.
1088 sessBaselineMsgs = fullMsgCount
1089 persistMu.Unlock()
1090 // Re-scope the swarm dashboard to the new session so /swarm
1091 // only shows agents this session spawned. swarmMgr may be nil
1092 // here if we haven't reached the construction site yet (it
1093 // shouldn't be, since the interactive loop is what triggers
1094 // loadSession, but the nil check is cheap insurance).
1095 if swarmMgr != nil && newSess != nil {
1096 swarmMgr.SetActiveSession(newSess.ID)
1097 }
1098 return nil
1099 }
1100
1101 // changeCWD switches the running session to a new working directory.
1102 // Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
1103 // /cd slash command (which itself is only fired by the workspaces
1104 // extension's panel-key Enter handler today; the user can type /cd
1105 // directly but it's not in autocomplete / help / the README).
1106 //
1107 // Steps, in order:
1108 // 1. resolve + validate the new path (~ expansion, abs/rel)
1109 // 2. close the current session, flushing pending messages
1110 // 3. mutate captured args.CWD + r.CWD so future buildAgent
1111 // calls bind to the new cwd
1112 // 4. re-root the shared sandbox («·«) so /jail follows the
1113 // session into the new cwd instead of widening or silently
1114 // dropping
1115 // 5. rebuild the agent via buildAgent() so tools, AGENTS.md
1116 // addendum, system prompt, sessions dir all bind correctly
1117 // 6. open a fresh session in the new cwd's bucket
1118 // 7. push the new state into the running Interactive
1119 // 8. re-scope the swarm dashboard to the freshly-opened session
1120 //
1121 // The /jail state is preserved verbatim: if the sandbox was locked
1122 // to the old cwd, it stays locked, just re-pointed at the new one.
1123 changeCWD := func(path string) error {
1124 if path == "" {
1125 return fmt.Errorf("empty path")
1126 }
1127 // ~ expansion.
1128 if path == "~" || strings.HasPrefix(path, "~/") {
1129 home, herr := os.UserHomeDir()
1130 if herr != nil || home == "" {
1131 return fmt.Errorf("cannot expand ~: %v", herr)
1132 }
1133 if path == "~" {
1134 path = home
1135 } else {
1136 path = filepath.Join(home, path[2:])
1137 }
1138 }
1139 if !filepath.IsAbs(path) {
1140 path = filepath.Join(args.CWD, path)
1141 }
1142 absPath, err := filepath.Abs(path)
1143 if err != nil {
1144 return err
1145 }
1146 info, err := os.Stat(absPath)
1147 if err != nil {
1148 return err
1149 }
1150 if !info.IsDir() {
1151 return fmt.Errorf("not a directory: %s", absPath)
1152 }
1153
1154 currentAg := ag
1155 if currentAg == nil {
1156 return fmt.Errorf("no agent running; log in first")
1157 }
1158
1159 // Close the current session before we drop the reference.
1160 // Per-message persistence keeps it current already; this is
1161 // a defensive flush + final fsync via Close.
1162 persistMu.Lock()
1163 if sess != nil {
1164 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1165 _ = sess.Close()
1166 sess = nil
1167 }
1168 sessBaselineMsgs = 0
1169 persistMu.Unlock()
1170 extMgr.EndSession("cwd_change")
1171
1172 // Mutate captured state so subsequent agent rebuilds and
1173 // session opens see the new cwd.
1174 wasJailed := sharedSandbox != nil && sharedSandbox.Locked()
1175 args.CWD = absPath
1176 r.CWD = absPath
1177 if args.PermissionSet != nil {
1178 expanded := args.PermissionSet.Expand(absPath, args.AgentDataDir)
1179 args.PermissionSet = &expanded
1180 }
1181 if sharedSandbox != nil {
1182 sharedSandbox.Root = absPath
1183 if wasJailed {
1184 sharedSandbox.Lock()
1185 } else {
1186 sharedSandbox.Unlock()
1187 }
1188 }
1189
1190 // Rebuild the agent so tools / AGENTS.md / system prompt
1191 // re-bind to the new cwd. buildAgent() reads from args + r.
1192 newAg, newProvider, newModel, berr := buildAgent()
1193 if berr != nil {
1194 return fmt.Errorf("rebuild agent: %v", berr)
1195 }
1196 ag = newAg
1197
1198 // Fresh session in the new cwd's bucket. We bypass
1199 // openOrCreateSession's --continue / --resume branches
1200 // because /cd's semantics are "start fresh here", matching
1201 // what relaunching `zot --cwd <path>` would do today.
1202 if !args.NoSess {
1203 newRoot := agentSessionsRoot(ZotHome(), args)
1204 core.PruneEmptySessions(newRoot, absPath)
1205 newSess, serr := core.NewSession(newRoot, absPath, newProvider, newModel, version)
1206 if serr != nil {
1207 return fmt.Errorf("open session in %s: %v", absPath, serr)
1208 }
1209 persistMu.Lock()
1210 sess = newSess
1211 sessBaselineMsgs = 0
1212 persistMu.Unlock()
1213 bindAgentSession(newAg, newSess)
1214 }
1215
1216 r.Provider = newProvider
1217 r.Model = newModel
1218 r.Reasoning = newAg.Reasoning
1219 setZotSessionEnvironment(r, sess)
1220 startExtensionSession(extMgr, newAg, absPath, "cwd_change")
1221
1222 // Push the new state into the running Interactive.
1223 if iv != nil {
1224 startupPaths := instructionContextPaths(loadAgentsContext(absPath, ZotHome()))
1225 iv.ApplyChangedCWDWithStartupContext(newAg, newProvider, newModel, absPath, startupPaths)
1226 }
1227
1228 // Re-scope the swarm dashboard to the new session.
1229 if swarmMgr != nil {
1230 sessionID, _ := extMgr.SessionContext()
1231 swarmMgr.SetActiveSession(sessionID)
1232 }
1233 return nil
1234 }
1235
1236 term := tui.NewProcTerm()
1237
1238 // Kick off the async update check so the banner can appear when the
1239 // http response eventually arrives (usually <1s on cached DNS). Map
1240 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
1241 updateCh := make(chan modes.UpdateInfo, 1)
1242 go func() {
1243 defer close(updateCh)
1244 src := <-CheckForUpdateAsync(ZotHome(), version)
1245 updateCh <- modes.UpdateInfo{
1246 Current: src.Current,
1247 Latest: src.Latest,
1248 Available: src.Available,
1249 URL: src.URL,
1250 }
1251 }()
1252
1253 // Changelog: when the running version differs from the last
1254 // version whose release notes the user dismissed, fetch the
1255 // release body from GitHub and have the TUI show it once. On
1256 // first-ever launch (no prior LastChangelogShown), seed the
1257 // stored version silently — don't dump release notes at someone
1258 // who just installed.
1259 changelogCh := make(chan modes.ChangelogPayload, 1)
1260 go func() {
1261 defer close(changelogCh)
1262 cfg, _ := LoadConfig()
1263 if cfg.LastChangelogShown == "" {
1264 SeedChangelogVersion(version)
1265 return
1266 }
1267 if !ShouldShowChangelog(version, cfg) {
1268 return
1269 }
1270 info := <-FetchChangelogAsync(version)
1271 if info.Body == "" {
1272 return
1273 }
1274 // For dev builds (0.0.0), skip if the latest release was
1275 // already shown (stored by the dismiss callback).
1276 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
1277 return
1278 }
1279 changelogCh <- modes.ChangelogPayload{
1280 Version: info.Version,
1281 Body: info.Body,
1282 URL: info.URL,
1283 }
1284 }()
1285
1286 initialCfg, _ := LoadConfig()
1287 quickModelShortcuts := make([]modes.QuickModelShortcut, len(initialCfg.QuickModelShortcuts))
1288 for idx, s := range initialCfg.QuickModelShortcuts {
1289 quickModelShortcuts[idx] = modes.QuickModelShortcut{Provider: s.Provider, Model: s.Model}
1290 }
1291 theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
1292 if themeErr != nil {
1293 fmt.Fprintln(os.Stderr, "theme load:", themeErr)
1294 if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
1295 initialCfg.Theme = ""
1296 _ = SaveConfig(initialCfg)
1297 }
1298 }
1299
1300 // swarmMgr was constructed and reloaded earlier (before the agent
1301 // build, so the auto-swarm tool could capture it). Here we just
1302 // scope the dashboard to the active host session so /swarm only
1303 // shows agents this session spawned (and any pre-upgrade unscoped
1304 // agents — see SnapshotAll docs). Updated again whenever the
1305 // user swaps sessions via loadSession below.
1306 sessionID, _ := extMgr.SessionContext()
1307 swarmMgr.SetActiveSession(sessionID)
1308 // Best-effort shutdown on interactive exit: stop all running
1309 // agents so they don't outlive their parent zot.
1310 defer func() {
1311 shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
1312 defer cancel()
1313 swarmMgr.Shutdown(shutdownCtx)
1314 }()
1315
1316 var startupSkills []*skills.Skill
1317 if r.SkillTool != nil {
1318 startupSkills = r.SkillTool.Skills()
1319 }
1320
1321 iv = modes.NewInteractive(modes.InteractiveConfig{
1322 Terminal: term,
1323 Theme: theme,
1324 InlineImagesEnabled: initialCfg.InlineImagesEnabled,
1325 AutoSwarmEnabled: initialCfg.AutoSwarmEnabled,
1326 AutoCompactThreshold: initialCfg.AutoCompactThreshold,
1327 JailByDefault: initialCfg.JailByDefault,
1328 PowerShellEnabled: initialCfg.PowerShellEnabled,
1329 ToolSelectionExplicit: len(args.Tools) > 0,
1330 OpenRouterServerToolsEnabled: initialCfg.OpenRouterServerToolsEnabled,
1331 OpenRouterServerToolCallLimit: initialCfg.OpenRouterServerToolCallLimit,
1332 NoTools: args.NoTools,
1333 QuickModelShortcuts: quickModelShortcuts,
1334 RecursiveFileSuggest: initialCfg.RecursiveFileSuggest,
1335 FuzzySkillSuggest: initialCfg.FuzzySkillSuggest,
1336 RespectGitignore: initialCfg.RespectGitignore,
1337 CompactMode: initialCfg.CompactMode,
1338 CollapseToolCall: initialCfg.CollapseToolCall,
1339 TUIInputStyle: initialCfg.TUIInputStyle,
1340 TUIStatusPosition: initialCfg.TUIStatusPosition,
1341 TUIWorkingPosition: initialCfg.TUIWorkingPosition,
1342 ThemeName: initialCfg.Theme,
1343 FlatTools: initialCfg.FlatToolRender(),
1344 CompactUser: initialCfg.CompactUserInput(),
1345 ExtensionThemes: extMgr.ThemeOptions,
1346 AutoSwarmSystemAddendum: AutoSwarmSystemAddendum,
1347 SettingsStore: configSettingsStore{},
1348 Model: r.Model,
1349 Provider: r.Provider,
1350 AuthMethod: r.AuthMethod,
1351 BaseURL: r.BaseURL,
1352 Reasoning: r.Reasoning,
1353 SystemPrompt: r.SystemPrompt,
1354 Tools: r.ToolRegistry,
1355 MaxSteps: r.MaxSteps,
1356 CWD: r.CWD,
1357 StartupAgentName: args.AgentName,
1358 StartupContextPaths: instructionContextPaths(r.ContextFiles),
1359 StartupExtensionNames: startupExtensionNames(extMgr.All()),
1360 StartupExtensionErrors: startupExtensionErrors,
1361 StartupSkillNames: startupSkillNames(startupSkills),
1362 ShowInstructionsAtStartup: initialCfg.ShowInstructionsAtStartup,
1363 ZotHome: ZotHome(),
1364 SessionsRoot: agentSessionsRoot(ZotHome(), args),
1365 Version: version,
1366 UpdateInfoChan: updateCh,
1367 Sandbox: sharedSandbox,
1368 Agent: ag,
1369 InitialInput: args.Prompt,
1370 StartupPre: args.StartupPre,
1371 OnStartupPreDone: func() {
1372 // entry.pre often installs skills/extensions; rediscover them
1373 // before the user starts a model turn.
1374 current := liveInteractiveAgent(iv, ag)
1375 if extMgr != nil {
1376 _ = extMgr.Reload(context.Background(), 2*time.Second)
1377 }
1378 if current != nil {
1379 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
1380 }
1381 },
1382 AuthManager: mgr,
1383 LlamaCPPConfig: ResolveLlamaCPPConfig,
1384 RefreshLlamaCPPModels: RefreshLlamaCPPModels,
1385 RefreshLMStudioModels: RefreshLMStudioModels,
1386 LMStudioConfigured: LMStudioConfigured,
1387 RefreshCustomProviderModels: RefreshCustomProviderModels,
1388 CustomDiscoveryConfigured: CustomDiscoveryConfigured,
1389 BuildAgent: buildAgent,
1390 SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
1391 BuildAgentFor: buildAgentFor,
1392 BuildAgentForRescue: buildAgentForRescue,
1393 LoggedInProviders: func() []string {
1394 var out []string
1395 seen := map[string]bool{}
1396 for _, p := range knownProviders {
1397 if CredentialAvailable(p) && !seen[p] {
1398 out = append(out, p)
1399 seen[p] = true
1400 }
1401 }
1402 // Include custom providers that have credentials stored.
1403 for p := range provider.CustomProviders() {
1404 if CredentialAvailable(p) && !seen[p] {
1405 out = append(out, p)
1406 seen[p] = true
1407 }
1408 }
1409 // Ollama models are always available (no auth needed).
1410 if !seen["ollama"] {
1411 out = append(out, "ollama")
1412 }
1413 return out
1414 },
1415 LoadSession: loadSession,
1416 ChangeCWD: changeCWD,
1417 CurrentSessionPath: func() string {
1418 if sess == nil {
1419 return ""
1420 }
1421 return sess.Path
1422 },
1423 FlushSession: func() {
1424 // Append any not-yet-persisted agent messages to the
1425 // current session file, then advance the baseline so
1426 // the final WriteNewTranscript at exit doesn't write
1427 // duplicates. Per-message persistence keeps the on-
1428 // disk file current already, so this is mostly a
1429 // defensive flush — still needed for /session export
1430 // to guarantee the exported bytes include the very
1431 // last in-flight turn.
1432 currentAg := iv.Agent()
1433 if currentAg == nil {
1434 return
1435 }
1436 persistMu.Lock()
1437 defer persistMu.Unlock()
1438 if sess == nil {
1439 return
1440 }
1441 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1442 sessBaselineMsgs = len(currentAg.Messages())
1443 },
1444 Extensions: extMgr,
1445 Swarm: swarmMgr,
1446 ChangelogChan: changelogCh,
1447 OnChangelogDismiss: func() {
1448 // For dev builds (0.0.0) store the actual release version
1449 // so the same changelog doesn't show again next launch.
1450 // For real builds, store the binary version.
1451 v := version
1452 if v == "0.0.0" {
1453 if iv != nil && iv.ChangelogVersion() != "" {
1454 v = iv.ChangelogVersion()
1455 }
1456 }
1457 _ = MarkChangelogShown(v)
1458 },
1459 SkillSnapshot: func() []*skills.Skill {
1460 if args.NoSkill {
1461 // --no-skill: nothing for the picker to show.
1462 return nil
1463 }
1464 // Re-discover so the picker reflects edits made during
1465 // the session. Cheap; SKILL.md files are small. Filter
1466 // out built-in skills — they're hidden from user-facing
1467 // surfaces because they're implementation detail; the
1468 // model still sees them through the system-prompt
1469 // manifest and the skill tool.
1470 userHome, _ := os.UserHomeDir()
1471 var sources []skills.Source
1472 if args.WithSkills {
1473 sources = append(sources, skills.SearchSources(ZotHome(), r.CWD, userHome)...)
1474 }
1475 if !args.NoExt || len(args.Exts) > 0 {
1476 extSources, _ := extensions.PlanSkillSources(ZotHome(), r.CWD, args.Exts, !args.NoExt)
1477 sources = append(extSources, sources...)
1478 }
1479 list, _ := skills.DiscoverSources(sources, true)
1480 return skills.VisibleSkills(list)
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 if args.NoSess {
1577 setZotSessionEnvironment(r, nil)
1578 return nil, nil
1579 }
1580 // Sweep meta-only files left over from older zot versions (and from
1581 // any session that crashed before its first AppendMessage). Cheap;
1582 // reads the first few bytes of each file in the cwd's session dir.
1583 sessionsRoot := agentSessionsRoot(ZotHome(), args)
1584 core.PruneEmptySessions(sessionsRoot, args.CWD)
1585 var (
1586 s *core.Session
1587 msgs []provider.Message
1588 err error
1589 )
1590 switch {
1591 case args.Session != "":
1592 s, msgs, err = core.OpenSession(args.Session)
1593 // The swarm-agent child passes a fixed --session path that
1594 // may not exist yet on first Spawn. Treat ENOENT as "create
1595 // a fresh session AT THIS PATH" so the conversation actually
1596 // gets persisted; without this fallback the swarm child runs
1597 // with sess==nil and every Resume re-starts with no memory
1598 // of the prior turns. Other openers (--continue / --resume /
1599 // the picker) never see ENOENT here because they only choose
1600 // paths that already exist on disk.
1601 if err != nil && errors.Is(err, os.ErrNotExist) {
1602 s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1603 msgs = nil
1604 }
1605 case args.Continue:
1606 latest := core.LatestSession(sessionsRoot, args.CWD)
1607 if latest != "" {
1608 s, msgs, err = core.OpenSession(latest)
1609 }
1610 case args.Resume:
1611 picked, perr := pickSession(sessionsRoot, args.CWD)
1612 if perr != nil {
1613 return nil, perr
1614 }
1615 if picked != "" {
1616 s, msgs, err = core.OpenSession(picked)
1617 }
1618 }
1619 if err != nil {
1620 return nil, err
1621 }
1622 if s == nil {
1623 s, err = core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
1624 if err != nil {
1625 return nil, err
1626 }
1627 } else {
1628 ag.SetMessages(msgs)
1629 if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1630 ag.SeedCost(cum)
1631 ag.SeedLastTurnUsage(last)
1632 }
1633 }
1634 bindAgentSession(ag, s)
1635 setZotSessionEnvironment(r, s)
1636 return s, nil
1637}
1638
1639// setZotSessionEnvironment publishes the non-secret runtime metadata that
1640// zot's child processes can use for attribution and diagnostics.
1641func setZotSessionEnvironment(r Resolved, sess *core.Session) {
1642 values := map[string]string{
1643 "ZOT_PROVIDER": r.Provider,
1644 "ZOT_MODEL": r.Model,
1645 "ZOT_REASONING_LEVEL": r.Reasoning,
1646 }
1647 if sess != nil {
1648 values["ZOT_SESSION_ID"] = sess.ID
1649 values["ZOT_SESSION_FILE"] = sess.Path
1650 }
1651 for _, name := range []string{"ZOT_SESSION_ID", "ZOT_SESSION_FILE", "ZOT_PROVIDER", "ZOT_MODEL", "ZOT_REASONING_LEVEL"} {
1652 if value := values[name]; value != "" {
1653 _ = os.Setenv(name, value)
1654 } else {
1655 _ = os.Unsetenv(name)
1656 }
1657 }
1658}
1659
1660func pickSession(root, cwd string) (string, error) {
1661 files := core.ListSessions(root, cwd)
1662 if len(files) == 0 {
1663 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1664 return "", nil
1665 }
1666 for i, f := range files {
1667 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
1668 }
1669 fmt.Fprint(os.Stderr, "pick #: ")
1670 rd := bufio.NewReader(os.Stdin)
1671 line, _ := rd.ReadString('\n')
1672 line = strings.TrimSpace(line)
1673 var n int
1674 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1675 return "", fmt.Errorf("invalid selection")
1676 }
1677 return files[n-1], nil
1678}
1679
1680// WriteNewTranscript appends only messages after index `from` from the
1681// agent's transcript to the session. Used by callers that don't hold
1682// the persistMu (non-interactive print/json modes which run a single
1683// turn under their own goroutine).
1684func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1685 writeNewTranscriptLocked(ag, sess, from)
1686}
1687
1688// bindAgentSession stamps the zot session id onto the agent so providers
1689// that support sticky routing (OpenRouter session_id) can reuse it.
1690// No-op when persistence is disabled.
1691func bindAgentSession(ag *core.Agent, sess *core.Session) {
1692 if ag == nil || sess == nil {
1693 return
1694 }
1695 ag.SessionID = sess.ID
1696}
1697
1698// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1699// suffix marks that interactive callers must hold persistMu when
1700// invoking it so concurrent appends from the agent loop don't race
1701// with this catch-up flush.
1702func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1703 if sess == nil || ag == nil {
1704 return
1705 }
1706 msgs := ag.Messages()
1707 for i := from; i < len(msgs); i++ {
1708 _ = sess.AppendMessage(msgs[i])
1709 }
1710 cum := ag.Cost()
1711 _ = sess.AppendUsage(cum, cum)
1712}
1713
1714func argsForStdin(rawArgs []string, mode os.FileMode) []string {
1715 if mode&os.ModeCharDevice != 0 {
1716 return rawArgs
1717 }
1718 return append([]string{"--print"}, rawArgs...)
1719}
1720
1721func combinePromptInput(stdin, positional string) string {
1722 parts := make([]string, 0, 2)
1723 if stdin = strings.TrimSpace(stdin); stdin != "" {
1724 parts = append(parts, stdin)
1725 }
1726 if positional = strings.TrimSpace(positional); positional != "" {
1727 parts = append(parts, positional)
1728 }
1729 return strings.Join(parts, "\n")
1730}
1731
1732func readAllStdin() (string, error) {
1733 fi, err := os.Stdin.Stat()
1734 if err != nil {
1735 return "", err
1736 }
1737 if (fi.Mode() & os.ModeCharDevice) != 0 {
1738 return "", nil
1739 }
1740 b, err := io.ReadAll(os.Stdin)
1741 return string(b), err
1742}
1743
1744func printModels() {
1745 models := provider.Active()
1746
1747 // Compute column widths from actual data so wide providers (e.g.
1748 // xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1749 // `name` column off-screen. Floors mirror the historical layout so
1750 // short catalogs look the same as before.
1751 provW, idW, srcW := len("provider"), len("model id"), len("source")
1752 for _, m := range models {
1753 if w := len(m.Provider); w > provW {
1754 provW = w
1755 }
1756 if w := len(m.ID); w > idW {
1757 idW = w
1758 }
1759 source := m.Source
1760 if source == "" {
1761 source = "catalog"
1762 }
1763 if m.Speculative {
1764 source = "speculative"
1765 }
1766 if w := len(source); w > srcW {
1767 srcW = w
1768 }
1769 }
1770
1771 header := fmt.Sprintf("%-*s %-*s %8s %8s %s %-*s %s",
1772 provW, "provider",
1773 idW, "model id",
1774 "context", "max-out", "reasoning",
1775 srcW, "source",
1776 "name")
1777 fmt.Println(header)
1778
1779 for _, m := range models {
1780 reason := " "
1781 if m.Reasoning {
1782 reason = "✓"
1783 }
1784 source := m.Source
1785 if source == "" {
1786 source = "catalog"
1787 }
1788 if m.Speculative {
1789 source = "speculative"
1790 }
1791 fmt.Printf("%-*s %-*s %8d %8d %s %-*s %s\n",
1792 provW, m.Provider,
1793 idW, m.ID,
1794 m.ContextWindow, m.MaxOutput,
1795 reason,
1796 srcW, source,
1797 m.DisplayName)
1798 }
1799}