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