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