pkg/service/agent/provider_host.go

package agent

// Provider-owned exports use ordinary macro calls and tunnelstream byte owners.
// The service supplies connection identity and publishes Inventory; it does not
// choose upstream endpoints, credentials, or provider request policy.
import (
	"context"
	"crypto/sha256"
	"errors"
	"fmt"
	"net"
	"reflect"
	"sort"
	"sync"

	"git.cafe/ezterry/ez-agent/internal/tunnelstream"
	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/service/config"
	"git.cafe/ezterry/ez-agent/pkg/service/session"
)

const ProviderTunnelInfo = "IFO,Remote LLM provider tunnel,llmprovider,1"

var ErrProviderExportUnavailable = errors.New("provider export unavailable")

// ExternalHostChannel is the hosting seam for protocol-1 bridges. Implementors
// own raw process startup, hello validation/rewriting and model enforcement.
// The context owns the whole stream. No bridge is started for IFO or LIST.
type ExternalHostChannel func(context.Context, *config.Config, string, config.ProviderConfig, net.Conn) error

type ProviderHostOptions struct{ External ExternalHostChannel }

type ProviderExports struct {
	mu      sync.Mutex
	exports map[string]*ProviderExportRoute
	budget  *tunnelstream.Budget
	closed  bool
	options ProviderHostOptions
	// Test seam for admission failures without performing a live token refresh.
	resolveSubscription func(context.Context, *config.Config, string) (*config.SubscriptionAdmission, error)
	// Reuse the existing authorization watcher registration and shutdown owner,
	// without a leaf, storage, tools, or an agent execution.
	authorization Agent
}

// ProviderExportRoute pins one export generation. Old admissions remain bound
// to this object and cannot silently switch to a newly enabled provider.
type ProviderExportRoute struct {
	mu     sync.Mutex
	ctx    context.Context
	cancel context.CancelFunc
	cfg    *config.Config
	name   string
	pc     config.ProviderConfig
	// Fingerprint the resolved host key at publication, including environment
	// credentials whose values can change independently of the config snapshot.
	externalCredential [sha256.Size]byte
	host               *ProviderExports
	peers              map[string]*hostPeer
}
type hostResult struct {
	text    string
	failure bool
}
type hostPeer struct {
	server  *tunnelstream.Server
	mu      sync.Mutex
	pending map[string]chan hostResult
}

func NewProviderExports(opts ProviderHostOptions) *ProviderExports {
	if opts.External == nil {
		opts.External = serveExternalHost
	}
	return &ProviderExports{exports: make(map[string]*ProviderExportRoute), budget: tunnelstream.NewBudget(128), options: opts,
		resolveSubscription: func(ctx context.Context, cfg *config.Config, name string) (*config.SubscriptionAdmission, error) {
			return cfg.ResolveSubscriptionAdmission(ctx, name)
		},
	}
}

// Publish takes a validated, immutable user-config snapshot, never a project
// layer. Changed/withdrawn generations are cancelled before this returns.
func (h *ProviderExports) Publish(cfg *config.Config) {
	h.mu.Lock()
	if h.closed {
		h.mu.Unlock()
		return
	}
	var retired []*ProviderExportRoute
	for macro, route := range h.exports {
		pc, ok := cfg.Providers[route.name]
		credentialChanged := ok && pc.Type == "external" && sha256.Sum256([]byte(cfg.GetAPIKey(route.name))) != route.externalCredential
		if !ok || !cfg.ExportsProvider(route.name) || !reflect.DeepEqual(pc, route.pc) || credentialChanged {
			route.cancel()
			retired = append(retired, route)
			delete(h.exports, macro)
		}
	}
	for name, pc := range cfg.Providers {
		if !cfg.ExportsProvider(name) {
			continue
		}
		macro, err := config.ProviderExportMacroName(name)
		if err != nil {
			continue
		}
		if route := h.exports[macro]; route != nil {
			route.mu.Lock()
			route.cfg = cfg
			route.mu.Unlock()
			continue
		}
		ctx, cancel := context.WithCancel(context.Background())
		route := &ProviderExportRoute{ctx: ctx, cancel: cancel, cfg: cfg, name: name, pc: pc, host: h, peers: make(map[string]*hostPeer)}
		if pc.Type == "external" {
			route.externalCredential = sha256.Sum256([]byte(cfg.GetAPIKey(name)))
		}
		h.exports[macro] = route
	}
	h.mu.Unlock()
	for _, route := range retired {
		route.close()
	}
}
func (h *ProviderExports) Inventory() []protocol.MacroInfo {
	h.mu.Lock()
	defer h.mu.Unlock()
	out := make([]protocol.MacroInfo, 0, len(h.exports))
	for name := range h.exports {
		out = append(out, protocol.MacroInfo{Name: name, Description: "Remote LLM provider tunnel", Internal: true, Timeout: "30s"})
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
	return out
}
func (h *ProviderExports) Route(macro string) (*ProviderExportRoute, error) {
	h.mu.Lock()
	defer h.mu.Unlock()
	route := h.exports[macro]
	if route == nil || h.closed {
		return nil, ErrProviderExportUnavailable
	}
	return route, nil
}
func (h *ProviderExports) DropConnection(id string) {
	h.mu.Lock()
	var peers []*hostPeer
	for _, route := range h.exports {
		route.mu.Lock()
		if peer := route.peers[id]; peer != nil {
			delete(route.peers, id)
			peers = append(peers, peer)
		}
		route.mu.Unlock()
	}
	h.mu.Unlock()
	for _, peer := range peers {
		peer.server.Close()
	}
}
func (h *ProviderExports) Close() {
	h.mu.Lock()
	h.closed = true
	var routes []*ProviderExportRoute
	for _, r := range h.exports {
		r.cancel()
		routes = append(routes, r)
	}
	clear(h.exports)
	h.mu.Unlock()
	for _, r := range routes {
		r.close()
	}
	h.authorization.Close()
}
func (r *ProviderExportRoute) close() {
	r.cancel()
	r.mu.Lock()
	peers := r.peers
	r.peers = make(map[string]*hostPeer)
	r.mu.Unlock()
	for _, p := range peers {
		p.server.Close()
	}
}

// connectionClosed must be the exact caller connection's lifetime signal.
func (r *ProviderExportRoute) Call(ctx context.Context, connectionID string, connectionClosed <-chan struct{}, row string) (string, error) {
	r.mu.Lock()
	select {
	case <-connectionClosed:
		r.mu.Unlock()
		return "", ErrProviderExportUnavailable
	default:
	}
	if r.ctx.Err() != nil {
		r.mu.Unlock()
		return "", ErrProviderExportUnavailable
	}
	if row == "IFO" {
		r.mu.Unlock()
		return ProviderTunnelInfo, nil
	}
	if row == "LIST" {
		pc, name, cfg := r.pc, r.name, r.cfg
		r.mu.Unlock()
		source := ""
		if len(pc.Models) > 0 {
			// Authentication is provider-wide. Use only the immutable host
			// snapshot, without opening a bridge or refreshing credentials.
			source = ResolveAccessSource(cfg, name+"/"+pc.Models[0].Name)
			if source == "unknown" {
				// Config alone supplies no new provider observation.
				source = ""
			}
		}
		return EncodeProviderCatalog(name, pc, source)
	}
	peer := r.peers[connectionID]
	if peer == nil {
		peer = &hostPeer{pending: make(map[string]chan hostResult)}
		p := peer
		macro, _ := config.ProviderExportMacroName(r.name)
		peer.server = tunnelstream.NewServer(tunnelstream.ServerOptions{Context: r.ctx, Macro: macro, Info: ProviderTunnelInfo, Budget: r.host.budget,
			ValidateInit: func(fields []string) error {
				if len(fields) != 5 || fields[2] != "llmprovider" || fields[3] != r.name || fields[4] != r.pc.Type || r.ctx.Err() != nil {
					return ErrProviderExportUnavailable
				}
				return nil
			},
			Open: r.open,
			Reply: func(id, text string, failure bool) {
				p.mu.Lock()
				ch := p.pending[id]
				p.mu.Unlock()
				if ch != nil {
					select {
					case ch <- hostResult{text, failure}:
					default:
					}
				}
			},
			Fail: func() { go p.server.Close() },
		})
		r.peers[connectionID] = peer
		go func() {
			select {
			case <-connectionClosed:
			case <-r.ctx.Done():
			}
			p.server.Close()
			r.mu.Lock()
			if r.peers[connectionID] == p {
				delete(r.peers, connectionID)
			}
			r.mu.Unlock()
		}()
	}
	// Register and dispatch under the route lock so retirement cannot close a
	// server and then let a delayed caller add new work to it.
	id := session.NewIDBytes("he_", 8)
	ch := make(chan hostResult, 1)
	peer.mu.Lock()
	peer.pending[id] = ch
	peer.mu.Unlock()
	macro, _ := config.ProviderExportMacroName(r.name)
	peer.server.Call(ezagentapi.MacroCall{MacroCallID: id, MacroName: macro, ParamString: row})
	r.mu.Unlock()
	defer func() { peer.mu.Lock(); delete(peer.pending, id); peer.mu.Unlock() }()
	select {
	case result := <-ch:
		if result.failure {
			return "", fmt.Errorf("provider tunnel: %s", result.text)
		}
		return result.text, nil
	case <-r.ctx.Done():
		return "", ErrProviderExportUnavailable
	case <-connectionClosed:
		return "", ErrProviderExportUnavailable
	case <-ctx.Done():
		return "", ctx.Err()
	}
}
func (r *ProviderExportRoute) open(ctx context.Context, _ []string) (net.Conn, error) {
	if ctx.Err() != nil {
		return nil, ErrProviderExportUnavailable
	}
	consumer, host := net.Pipe()
	applicationContext, cancel := context.WithCancel(ctx)
	done := make(chan struct{})
	r.mu.Lock()
	cfg := r.cfg
	r.mu.Unlock()
	go func() {
		defer close(done)
		defer host.Close()
		stop := context.AfterFunc(applicationContext, func() { host.Close() })
		defer stop()
		if r.pc.Type == "external" {
			_ = r.host.options.External(applicationContext, cfg, r.name, r.pc, host)
			return
		}
		r.serveHTTP(applicationContext, cfg, host)
	}()
	return &hostApplicationConn{Conn: consumer, cancel: cancel, done: done}, nil
}

// Tunnel retirement joins the application/upstream owner as well as the byte
// stream. In particular, external channel cleanup must finish before the
// admission slot can be reused or export withdrawal returns.
type hostApplicationConn struct {
	net.Conn
	cancel context.CancelFunc
	done   <-chan struct{}
	once   sync.Once
}

func (c *hostApplicationConn) Close() error {
	c.once.Do(func() { c.cancel(); c.Conn.Close(); <-c.done })
	return nil
}