cmd/ez-agent-builtin/internal/builtin/buffer/meta.go

package buffer

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"sort"
	"strconv"
	"strings"
	"unicode/utf8"

	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/modes"
	"git.cafe/ezterry/ez-agent/internal/frontend"
	"git.cafe/ezterry/ez-agent/internal/webfetchhelp"
	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
)

type metaRPC interface {
	ListLeavesFiltered(context.Context, string, string, []string, bool) ([]protocol.LeafInfo, error)
	ListHistorySnapshot(context.Context, string) (ezagentapi.HistorySnapshot, error)
	GetTurn(context.Context, string) (protocol.TurnContent, error)
	ListModelsForLeaf(context.Context, string) ([]protocol.ModelEntry, error)
	LeafStats(context.Context, string) (protocol.LeafStatsResponse, error)
	GetEffectiveConfig(context.Context, string) (protocol.EffectiveConfig, error)
	ListLeafConfig(context.Context, string) ([]protocol.LeafConfigListEntry, error)
}

const metaDiscoveryHint = `The official list of meta buffer calls is in meta:index, with relevant skills. Retry with a name listed there.`

const metaIndex = `Meta buffers are read-only and generated in memory. This index is endpoint names only; skill:reflection holds the details for session, leaf, history, turn, model, and mode metadata. Only these exact names exist:

- meta:index — this list.
- meta:session/current — current leaf: model, thinking level, context estimate, turn count, and state.
- meta:session/<leaf-id> — the same facts for a known leaf ID.
- meta:leaves/active — running and aborting leaves across all working directories.
- meta:history/<leaf-id> — visible turn summaries back to the latest virtual root; use current for this leaf.
- meta:last-turn/<leaf-id> — the canonical tip turn, including a draft; use current for this leaf.
- meta:turn/<turn-id> — persisted turn by ID.
- meta:models — models effective for this leaf, with context limits and thinking levels.
- meta:modes — modes effective for this leaf.
- meta:tasks/current — active run-cmd tasks in this leaf (see skill:command-tasks).
- meta:bash-<task-id>/state — one background command's state; copy the exact name from its result.
- meta:ruby-<task-id>/state — one background Ruby command's state; copy the exact name from its result.
- meta:webfetch-help — ez-agent-webfetch help; topics /http, /html, /websocket, /framed, /mcp, /all.

There are no other meta buffers; do not invent names. To interpret or change session, leaf, history, turn, model, or mode metadata — or to locate AGENTS.md, skills, and configuration — read skill:reflection.
`

func unknownMetaBuffer(name string) error {
	return fmt.Errorf("unknown meta buffer: %s. %s", name, metaDiscoveryHint)
}

func parseMetaName(name, currentLeaf string) (kind, leafID string, err error) {
	switch name {
	case "meta:models":
		return "models", currentLeaf, nil
	case "meta:modes":
		return "modes", currentLeaf, nil
	case "meta:leaves/active":
		return "active", "", nil
	case "meta:session/current":
		if currentLeaf == "" {
			return "", "", fmt.Errorf("cannot resolve meta:session/current: tool call has no leaf ID")
		}
		return "session", currentLeaf, nil
	}
	for _, entry := range []struct{ prefix, kind string }{
		{"meta:history/", "history"}, {"meta:last-turn/", "last-turn"}, {"meta:turn/", "turn"},
	} {
		if strings.HasPrefix(name, entry.prefix) {
			id := strings.TrimPrefix(name, entry.prefix)
			if id == "" || strings.Contains(id, "/") {
				return "", "", fmt.Errorf("malformed meta buffer name: %s. %s", name, metaDiscoveryHint)
			}
			if entry.kind != "turn" && id == "current" {
				if currentLeaf == "" {
					return "", "", fmt.Errorf("cannot resolve %s: tool call has no leaf ID", name)
				}
				id = currentLeaf
			}
			return entry.kind, id, nil
		}
	}
	const prefix = "meta:session/"
	if strings.HasPrefix(name, prefix) {
		id := strings.TrimPrefix(name, prefix)
		if id == "" || strings.Contains(id, "/") {
			return "", "", fmt.Errorf("malformed meta buffer name: %s. %s", name, metaDiscoveryHint)
		}
		return "session", id, nil
	}
	return "", "", unknownMetaBuffer(name)
}

func formatMetaModels(models []protocol.ModelEntry) string {
	var out strings.Builder
	for _, model := range models {
		maxContext := "unknown"
		if model.MaxContext > 0 {
			maxContext = fmt.Sprint(model.MaxContext)
		}
		fmt.Fprintf(&out, "- %s ctx:%s thinking[%s]\n", model.Ref, maxContext, strings.Join(model.ThinkingLevels, ","))
	}
	return out.String()
}

func formatMetaModes(configured []modes.ModeConfig) string {
	var out strings.Builder
	for _, name := range modes.Names(configured) {
		fmt.Fprintf(&out, "- %s\n", name)
	}
	return out.String()
}

func generateMeta(ctx context.Context, client metaRPC, name, currentLeaf string) (string, error) {
	kind, leafID, err := parseMetaName(name, currentLeaf)
	if err != nil {
		return "", err
	}
	if kind == "history" || kind == "last-turn" {
		history, err := client.ListHistorySnapshot(ctx, leafID)
		if err != nil {
			return "", err
		}
		if kind == "history" {
			return metaJSON(struct {
				LeafID    string                 `json:"leaf_id"`
				TipTurnID string                 `json:"tip_turn_id"`
				Turns     []protocol.TurnSummary `json:"turns"`
			}{leafID, history.TipTurnID, history.Turns})
		}
		if history.TipTurnID == "" {
			return "No tip turn.\n", nil
		}
		leafID = history.TipTurnID
		kind = "turn"
	}
	if kind == "turn" {
		turn, err := client.GetTurn(ctx, leafID)
		if err != nil {
			return "", err
		}
		return metaJSON(turn)
	}
	if kind == "active" {
		leaves, err := client.ListLeavesFiltered(ctx, "", "", nil, true)
		if err != nil {
			return "", err
		}
		var out strings.Builder
		for _, leaf := range leaves {
			// Older daemons ignore the optional request field.
			if leaf.Status == "running" || leaf.Status == "aborting" {
				fmt.Fprintf(&out, "- id:%s state:%s root:%s name:%q model:%q temp:%t\n", leaf.ID, leaf.Status, leaf.RootID, leaf.Name, leaf.Model, leaf.IsTemp)
			}
		}
		if out.Len() == 0 {
			return "No active leaves.\n", nil
		}
		return out.String(), nil
	}
	if kind == "models" {
		models, err := client.ListModelsForLeaf(ctx, leafID)
		if err != nil {
			return "", err
		}
		return formatMetaModels(models), nil
	}
	if kind == "modes" {
		modes, err := modes.Fetch(ctx, client, leafID)
		if err != nil {
			return "", err
		}
		return formatMetaModes(modes), nil
	}
	stats, err := client.LeafStats(ctx, leafID)
	if err != nil {
		var serviceErr *ezagentapi.ServiceError
		if name != "meta:session/current" && errors.As(err, &serviceErr) && serviceErr.Code == "leaf_not_found" {
			return fmt.Sprintf("session: %s\nstate: not found\n", leafID), nil
		}
		return "", err
	}
	configs, err := client.ListLeafConfig(ctx, leafID)
	if err != nil {
		return "", err
	}
	var origin, parent string
	var modelInfoRef, modelInfoModel, rememberedMax string
	var hasOrigin, hasParent bool
	for _, entry := range configs {
		switch entry.Key {
		case "model_info_ref":
			modelInfoRef = entry.Value
		case "model_info_model":
			modelInfoModel = entry.Value
		case "model_max_context":
			rememberedMax = entry.Value
		case "session_origin":
			origin, hasOrigin = entry.Value, true
		case "parent_leaf":
			parent, hasParent = entry.Value, true
		}
	}
	maxContext := "unknown"
	if max, err := strconv.ParseUint(rememberedMax, 10, 64); err == nil && max > 0 && modelInfoRef == stats.Model && modelInfoModel != "" {
		// A short ref can resolve to another host after a default-source edit.
		// Effective config is local to the daemon; checking it opens no remote
		// discovery stream and does not mutate remembered leaf properties.
		if refs, err := frontend.LoadModelRefs(ctx, client, leafID); err == nil && refs.ResolvedRef(stats.Model) == modelInfoModel {
			maxContext = strconv.FormatUint(max, 10)
		}
	}
	if maxContext == "unknown" {
		models, err := client.ListModelsForLeaf(ctx, leafID)
		if err != nil {
			return "", err
		}
		for _, model := range models {
			if model.Ref == stats.Model && model.MaxContext > 0 {
				maxContext = fmt.Sprint(model.MaxContext)
				break
			}
		}
	}
	var out strings.Builder
	fmt.Fprintf(&out, "session: %s\n", stats.LeafID)
	if hasOrigin {
		fmt.Fprintf(&out, "origin: %s\n", origin)
	}
	if hasParent {
		fmt.Fprintf(&out, "parent: %s\n", parent)
	}
	fmt.Fprintf(&out, "model: %s\nthinking: %s\ncontext: %d/%s estimate\nturns: %d\nstate: %s\n",
		stats.Model, stats.ThinkingLevel, stats.ContextTokens, maxContext, stats.TurnCount, stats.State)
	return out.String(), nil
}

func metaJSON(value any) (string, error) {
	data, err := json.MarshalIndent(value, "", "  ")
	if err != nil {
		return "", err
	}
	return string(data) + "\n", nil
}

func metaLineCount(content string) int {
	if content == "" {
		return 0
	}
	return strings.Count(strings.TrimSuffix(content, "\n"), "\n") + 1
}

func sliceMeta(content, offsetText, lengthText string) (string, string, bool, error) {
	totalLines, totalBytes := metaLineCount(content), int64(len(content))
	offset, err := parseAddr(offsetText, bufferLines, 0)
	if err != nil {
		return "", "", false, fmt.Errorf("invalid offset: %v", err)
	}
	length := bufferAddr{unit: offset.unit}
	if lengthText == "" {
		if offset.unit == bufferLines {
			length.value = int64(totalLines) - offset.value
		} else {
			length.value = totalBytes - offset.value
		}
	} else if length, err = parseAddr(lengthText, bufferLines, 0); err != nil {
		return "", "", false, fmt.Errorf("invalid length: %v", err)
	}
	if offset.unit == bufferBytes {
		start := offset.value
		if start < 0 {
			start = totalBytes + start
		}
		if start < 0 {
			start = 0
		}
		if start > totalBytes {
			start = totalBytes
		}
		end := totalBytes
		if length.unit == bufferBytes {
			if length.value >= 0 {
				end = start + length.value
			} else {
				end = totalBytes + length.value
			}
		}
		if end < start {
			end = start
		}
		if end > totalBytes {
			end = totalBytes
		}
		b := []byte(content)
		for start < end && !utf8.RuneStart(b[start]) {
			start++
		}
		for end > start && !utf8.Valid(b[start:end]) {
			end--
		}
		return string(b[start:end]), fmt.Sprintf("bytes %d-%d", start, end-1), end < totalBytes, nil
	}
	lines := strings.Split(strings.TrimSuffix(content, "\n"), "\n")
	start := offset.value
	if start < 0 {
		start = int64(totalLines) + start
	}
	if start < 0 {
		start = 0
	}
	if start > int64(totalLines) {
		start = int64(totalLines)
	}
	end := int64(totalLines)
	if length.unit == bufferLines {
		if length.value >= 0 {
			end = start + length.value
		} else {
			end = int64(totalLines) + length.value
		}
	}
	if end < start {
		end = start
	}
	if end > int64(totalLines) {
		end = int64(totalLines)
	}
	selectedLines := lines[start:end]
	if length.unit == bufferBytes && length.value != 0 {
		contentB, truncated := truncateToBytes(selectedLines, int64(abs64(length.value)))
		return string(contentB), fmt.Sprintf("lines %d-%d (bytes truncated)", start, start+int64(countLines(contentB))-1), truncated, nil
	}
	selected := strings.Join(selectedLines, "\n")
	return selected, fmt.Sprintf("lines %d-%d", start, max(start, end-1)), end < int64(totalLines), nil
}

func (s *Service) handleMetaBuffer(ctx context.Context, tc ezagentapi.ToolCall, stat bool, offset, length string) {
	name, _ := tc.Arguments["buffer_name"].(string)
	content, static := webfetchhelp.Meta(name)
	var err error
	if !static {
		if name == "meta:index" {
			content = metaIndex
		} else if name == "meta:tasks/current" {
			if tc.LeafID == "" {
				err = fmt.Errorf("tool call has no leaf ID")
			} else if s.TaskSnapshot == nil {
				err = fmt.Errorf("command task metadata unavailable")
			} else {
				tasks := s.TaskSnapshot(tc.LeafID)
				sort.Slice(tasks, func(i, j int) bool { return tasks[i].ID < tasks[j].ID })
				var out strings.Builder
				for _, task := range tasks {
					fmt.Fprintf(&out, "id: %s\ninterpreter: %s\nbackground: %t\ncancelled: %t\n", task.ID, task.Interpreter, task.Background, task.Cancelled)
					for _, identity := range task.Buffers {
						fmt.Fprintf(&out, "buffer: %s\n", identity)
					}
					out.WriteByte('\n')
				}
				content = out.String()
			}
		} else if (strings.HasPrefix(name, "meta:bash-") || strings.HasPrefix(name, "meta:ruby-")) && s.CommandState != nil {
			content, err = s.CommandState(ctx, name)
		} else if strings.HasPrefix(name, "meta:webfetch-help") {
			err = unknownMetaBuffer(name)
		} else {
			content, err = generateMeta(ctx, s.client, name, tc.LeafID)
		}
	}
	if err != nil {
		s.sendToolResult(tc.ToolCallID, fmt.Sprintf("cannot read %s: %v", name, err), true, "buffer")
		return
	}
	lines, bytes := metaLineCount(content), int64(len(content))
	if stat {
		s.sendToolResult(tc.ToolCallID, formatStat(name, lines, bytes, true, "", ""), false, "Stat: "+name)
		return
	}
	showing, label, truncated := content, "complete", false
	if offset != "" || length != "" {
		showing, label, truncated, err = sliceMeta(content, offset, length)
		if err != nil {
			s.sendToolResult(tc.ToolCallID, err.Error(), true, "Read: "+name)
			return
		}
	}
	header := formatHeader(name, lines, bytes, true, label, truncated)
	s.sendToolResult(tc.ToolCallID, header+"\n\n"+showing, false, "Read: "+name+" "+label)
}