Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435package tui
import ( "albedo/cli/internal/config" "albedo/cli/internal/daemon" "context" "errors" "fmt" "net/url" "os" "path/filepath" "regexp" "slices" "strings" "sync/atomic"
tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi")
// CapabilityPageModel owns a dedicated session page for one source of agent// context. MCP servers are added and edited through one form (mcp_form.go).type CapabilityPageModel struct { Prefs config.CapabilityPrefs Conn *daemon.Connection Form *mcpForm SessionID, Workspace, Kind string Items []capabilityItem page Global, ExtensionEnabled, ConfirmExtension bool ConfirmDelete bool}type capabilityItem struct { ID, Title, Detail string Secrets daemon.MCPSecretNames Server config.MCPServer Draft bool}type capabilityLoadedMsg struct { Prefs config.CapabilityPrefs Err error Items []capabilityItem Gen int ExtensionEnabled bool}type capabilitySavedMsg struct { Err error Gen int}type CapabilityPageDoneMsg struct{}type CapabilityPageChangedMsg struct{}
type ChatOpenCapabilityPageMsg struct{ Kind string }
// Commands outlive closed pages; globally unique generations reject their replies.var capabilityGen atomic.Int64
func nextCapabilityGen() int { return int(capabilityGen.Add(1)) }
func NewCapabilityPageModel(conn *daemon.Connection, sessionID, workspace, kind string) CapabilityPageModel { // Pages open on the global defaults; s scopes changes to this session. return CapabilityPageModel{Conn: conn, SessionID: sessionID, Workspace: workspace, Kind: kind, Global: true, page: page{Loading: true, Generation: nextCapabilityGen()}}}func (m CapabilityPageModel) Init() tea.Cmd { return m.loadCmd(m.Generation) }func (m CapabilityPageModel) loadCmd(gen int) tea.Cmd { workspace, kind := m.Workspace, m.Kind return func() tea.Msg { settings, err := daemon.GetSettings(context.Background(), m.Conn) if err != nil { return capabilityLoadedMsg{Gen: gen, Err: err} } var items []capabilityItem switch kind { case "skills": items, err = discoverSkills(workspace) case "instructions": items = discoverInstructions(workspace) case "mcp": items = mcpItems(settings) default: err = errors.New("unknown capability page") } slices.SortFunc(items, func(a, b capabilityItem) int { return strings.Compare(a.ID, b.ID) }) enabled := true if err == nil && m.Conn != nil { path := fmt.Sprintf("/sessions/%s/extensions", url.PathEscape(m.SessionID)) var extensions []ExtensionItem extensions, err = daemon.Request[[]ExtensionItem](context.Background(), m.Conn, path, nil) if i := slices.IndexFunc(extensions, func(ext ExtensionItem) bool { return ext.Name == kind }); err == nil && i >= 0 { enabled = extensions[i].Enabled } } return capabilityLoadedMsg{Items: items, Prefs: settings.Capabilities, ExtensionEnabled: enabled, Gen: gen, Err: err} }}
// mcpItems lists the configured servers with the names of the secrets the// daemon holds for them (never their contents).func mcpItems(settings daemon.Settings) []capabilityItem { items := make([]capabilityItem, 0, len(settings.MCP)) for name, server := range settings.MCP { address := server.URL if server.Type == "stdio" { address = server.Command } items = append(items, capabilityItem{ID: name, Title: name, Detail: server.Type + " · " + address, Server: server, Secrets: settings.Credentials.MCP[name]}) } return items}
// Discovery mirrors the daemon's root ordering. Disabled entries remain listed;// the daemon's prepared catalog remains authoritative after a reload.func discoverSkills(workspace string) ([]capabilityItem, error) { userHome, _ := os.UserHomeDir() roots := []string{filepath.Join(workspace, ".albedo", "skills"), filepath.Join(workspace, ".agents", "skills"), filepath.Join(userHome, ".albedo", "skills"), filepath.Join(userHome, ".agents", "skills")} seen := map[string]bool{} var items []capabilityItem for _, root := range roots { dirs, err := os.ReadDir(root) if os.IsNotExist(err) { continue } if err != nil { return nil, err } for _, dir := range dirs { name := dir.Name() if seen[name] || !dir.IsDir() { continue } path := filepath.Join(root, name, "SKILL.md") info, err := os.Stat(path) if err != nil || !info.Mode().IsRegular() { continue } seen[name] = true items = append(items, capabilityItem{ID: name, Title: name, Detail: path}) } } return items, nil}func discoverInstructions(workspace string) []capabilityItem { var items []capabilityItem entries, _ := os.ReadDir(workspace) for _, e := range entries { if e.Type().IsRegular() && (strings.EqualFold(e.Name(), "AGENTS.md") || strings.EqualFold(e.Name(), "CLAUDE.md")) { items = append(items, capabilityItem{ID: "project:" + e.Name(), Title: e.Name(), Detail: filepath.Join(workspace, e.Name())}) } } userHome, _ := os.UserHomeDir() for _, group := range []struct{ scope, base string }{{"project", workspace}, {"global", userHome}} { for _, folder := range []string{".agents", ".albedo"} { path := filepath.Join(group.base, folder) subEntries, _ := os.ReadDir(path) for _, e := range subEntries { if !e.Type().IsRegular() || !strings.EqualFold(filepath.Ext(e.Name()), ".md") { continue } display := filepath.Join(folder, e.Name()) if group.scope == "global" { display = filepath.Join("~", folder, e.Name()) } items = append(items, capabilityItem{ID: group.scope + ":" + display, Title: display, Detail: filepath.Join(path, e.Name())}) } } } return items}
func (m CapabilityPageModel) enableExtensionCmd(gen int) tea.Cmd { return func() tea.Msg { path := fmt.Sprintf("/sessions/%s/extensions", url.PathEscape(m.SessionID)) _, err := daemon.Request[[]ExtensionItem](context.Background(), m.Conn, path, map[string]any{"name": m.Kind, "enabled": true}) return capabilitySavedMsg{Gen: gen, Err: err} }}
func (m CapabilityPageModel) toggleCmd(item capabilityItem, gen int) tea.Cmd { next := !m.selectedEnabled(item) scope := "session" if m.Global { scope = "global" } return func() tea.Msg { err := daemon.SetCapability(context.Background(), m.Conn, m.SessionID, m.Kind, item.ID, scope, &next) return capabilitySavedMsg{Gen: gen, Err: err} }}
var mcpHeaderName = regexp.MustCompile(`^[!#$%&'*+.^_` + "`" + `|~0-9A-Za-z-]+$`)var mcpEnvName = regexp.MustCompile(`^[A-Za-z_][A-Za-z_0-9]*$`)
// saveMCPCmd writes a server and its credentials together and reloads the// session once. If the reload fails (the server cannot connect), both are// restored, so a half-configured server is never left behind.func (m CapabilityPageModel) saveMCPCmd(sub mcpSubmission, gen int) tea.Cmd { return func() tea.Msg { return capabilitySavedMsg{Gen: gen, Err: daemon.SaveMCP(context.Background(), m.Conn, m.SessionID, sub.Name, &sub.Server, sub.Secrets)} }}
func (m CapabilityPageModel) deleteMCPCmd(name string, gen int) tea.Cmd { return func() tea.Msg { return capabilitySavedMsg{Gen: gen, Err: daemon.SaveMCP(context.Background(), m.Conn, m.SessionID, name, nil, nil)} }}
var mcpName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
// openForm starts adding a server, or editing the selected one with its// stored credentials summarized (never shown).func (m *CapabilityPageModel) openForm(edit bool) { m.Error, m.Notice = "", "" if !edit { m.Form = newMCPForm("", config.MCPServer{Type: "http"}, daemon.MCPSecretNames{}) return } item := m.Items[m.Cursor] m.Form = newMCPForm(item.ID, item.Server, item.Secrets)}
func (m CapabilityPageModel) save(cmd func(int) tea.Cmd) (CapabilityPageModel, tea.Cmd) { m.Saving = true m.Generation = nextCapabilityGen() return m, cmd(m.Generation)}
func (m CapabilityPageModel) Update(msg tea.Msg) (CapabilityPageModel, tea.Cmd) { switch msg := msg.(type) { case capabilityLoadedMsg: if !m.settle(msg.Gen, msg.Err, &m.Loading) { return m, nil } m.Cursor = reselect(m.Cursor, m.Items, msg.Items, func(item capabilityItem) string { return item.ID }) m.Items, m.Prefs, m.ExtensionEnabled, m.Error = msg.Items, msg.Prefs, msg.ExtensionEnabled, "" return m, nil case capabilitySavedMsg: if !m.settle(msg.Gen, msg.Err, &m.Saving) { return m, nil } m.Form = nil m.ConfirmDelete = false m.Notice = "Saved. Session reloaded." m.Loading, m.Generation = true, nextCapabilityGen() return m, tea.Batch(m.loadCmd(m.Generation), func() tea.Msg { return CapabilityPageChangedMsg{} }) case tea.PasteMsg: if m.Form == nil || m.Saving { return m, nil } _, cmd := m.Form.update(msg) return m, cmd case tea.KeyPressMsg: if m.Saving { return m, nil } if m.ConfirmExtension { switch msg.String() { case "esc": m.ConfirmExtension = false case "enter": m.ConfirmExtension = false return m.save(m.enableExtensionCmd) } return m, nil } if m.Form != nil { if msg.String() == "esc" { m.Form = nil m.Error = "" return m, nil } submit, cmd := m.Form.update(msg) if !submit { return m, cmd } sub, err := m.Form.submission(m.Items) if err != nil { m.Error = err.Error() return m, nil } m.Error = "" return m.save(func(gen int) tea.Cmd { return m.saveMCPCmd(sub, gen) }) } if m.ConfirmDelete { m.ConfirmDelete = false if msg.String() == "enter" && len(m.Items) > 0 { return m.save(func(gen int) tea.Cmd { return m.deleteMCPCmd(m.Items[m.Cursor].ID, gen) }) } return m, nil } if msg.String() == "esc" || msg.String() == "ctrl+c" { return m, func() tea.Msg { return CapabilityPageDoneMsg{} } } if m.Loading { return m, nil } if m.step(msg.String(), len(m.Items)) { return m, nil } mcp := m.Kind == "mcp" hasItems := len(m.Items) > 0 switch msg.String() { case "r": m.Loading = true m.Generation = nextCapabilityGen() return m, m.loadCmd(m.Generation) case "g", "s": m.Global = msg.String() == "g" case "E": if !m.ExtensionEnabled { m.ConfirmExtension = true } case "n": if mcp { m.openForm(false) } case "d": if mcp && hasItems { m.ConfirmDelete = true } case "e": // Re-enables a server switched off in extensions.json. if mcp && hasItems { if item := m.Items[m.Cursor]; item.Server.Enabled != nil && !*item.Server.Enabled { server := item.Server enabled := true server.Enabled = &enabled return m.save(func(gen int) tea.Cmd { return m.saveMCPCmd(mcpSubmission{Name: item.ID, Server: server, Secrets: daemon.MCPSecretsPatch{}}, gen) }) } } case "enter": if mcp && hasItems { m.openForm(true) } case "space": if hasItems { return m.save(func(gen int) tea.Cmd { return m.toggleCmd(m.Items[m.Cursor], gen) }) } } } return m, nil}func (m CapabilityPageModel) selectedEnabled(item capabilityItem) bool { if m.Global { if value, ok := m.Prefs.Global[m.Kind][item.ID]; ok { return value } return true } return m.Prefs.Enabled(m.SessionID, m.Kind, item.ID)}
func (m CapabilityPageModel) View() string { width := max(1, m.Width) mcp := m.Kind == "mcp" heading := map[string]string{"skills": "Skills", "instructions": "Instruction files", "mcp": "MCP servers"}[m.Kind] scope := "this session" if m.Global { scope = "global default" } rows := m.header("/"+m.Kind, scope) if m.Loading { rows = append(rows, DefaultStyles.Faint.Render("loading "+heading+"…")) return strings.Join(rows, "\n") } if m.ConfirmExtension || (m.ConfirmDelete && len(m.Items) > 0) { question := "This will reload this session. Enable the extension?" if m.ConfirmDelete { question = "Its stored credentials will also be removed. Delete MCP server " + m.Items[m.Cursor].ID + "?" } rows = append(rows, "") for line := range strings.SplitSeq(ansi.Wrap(question, width, " "), "\n") { rows = append(rows, DefaultStyles.Warning.Render(line)) } cancel := hint{"esc", "cancel"} if m.ConfirmDelete { cancel = hint{"any other key", "cancels"} } rows = append(rows, keyHints(hint{"enter", "confirm"}, cancel)) return m.fit(rows) } if !m.ExtensionEnabled { rows = append(rows, DefaultStyles.Warning.Render("Extension is off")+DefaultStyles.Decor.Render(" · ")+keyHints(hint{"E", "enable (reloads this session)"})) } if len(m.Items) == 0 { rows = append(rows, DefaultStyles.Faint.Render("No "+strings.ToLower(heading)+" found.")) } list := make([]string, len(m.Items)) for i, item := range m.Items { label := DefaultStyles.Success.Render("on ") if !m.selectedEnabled(item) || (mcp && item.Server.Enabled != nil && !*item.Server.Enabled) { label = DefaultStyles.Faint.Render("off") } detail := "" if mcp { detail = DefaultStyles.Faint.Render(" · " + item.Detail) } list[i] = listRow(i == m.Cursor, label+" "+item.Title+detail, width) } rows = append(rows, scrolled(list, m.Cursor, max(1, m.Height-12))...) switch { case m.Form != nil: rows = append(rows, "") rows = append(rows, m.Form.view(width)...) if m.Saving { rows = append(rows, "connecting and reloading…") } case m.Saving: rows = append(rows, "saving and reloading…") default: if len(m.Items) > 0 { selected := m.Items[m.Cursor] detail := selected.Detail if mcp { auth := "no credentials" if selected.Secrets.Any() { auth = "credentials stored privately" } detail += " · " + auth if selected.Server.Enabled != nil && !*selected.Server.Enabled { detail += " · disabled in extensions.json · press e to enable" } } rows = append(rows, "", DefaultStyles.Faint.Render(ansi.Truncate(detail, width, "…"))) } rows = append(rows, "", keyHints(hint{"↑↓", "select"}, hint{"space", "toggle"}, hint{"s", "session"}, hint{"g", "global"}, hint{"r", "refresh"}, hint{"esc", "back"})) if mcp { rows = append(rows, keyHints(hint{"n", "add server"}, hint{"enter", "edit"}, hint{"d", "delete"})) } } return m.fit(rows)}