package control import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "os" "path/filepath" "runtime" "strings" ) const MaxFrameBytes = 8 << 20 type Request struct { PluginID string `json:"plugin_id,omitempty"` Channel string `json:"channel,omitempty"` Message json.RawMessage `json:"message,omitempty"` RequestID json.RawMessage `json:"request_id,omitempty"` CloseInput bool `json:"close_input,omitempty"` } type Response struct { RequestID json.RawMessage `json:"request_id,omitempty"` Message json.RawMessage `json:"message,omitempty"` Error string `json:"error,omitempty"` } type Handler func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) // Target names one plugin channel that a control connection used. type Target struct { PluginID string Channel string } // Options configures a control server. OnSessionEnd runs once per connection // after its last in-flight call returns, with the channels it reached. type Options struct { OnSessionEnd func(session string, targets []Target) } type sessionKey struct{} // WithSession tags ctx with the control connection that issued a call. func WithSession(ctx context.Context, session string) context.Context { return context.WithValue(ctx, sessionKey{}, session) } // SessionFrom returns the control connection identifier carried by ctx. func SessionFrom(ctx context.Context) string { if ctx == nil { return "" } session, _ := ctx.Value(sessionKey{}).(string) return session } func newSessionID() string { var raw [12]byte if _, err := rand.Read(raw[:]); err != nil { return "" } return hex.EncodeToString(raw[:]) } // PipeName gives the desktop process and its CLI clients a deterministic // endpoint scoped to this installation path and Windows user. func PipeName() string { exe, err := os.Executable() if err != nil { exe = "reims-go" } return pipeNameForExecutable(exe) } func pipeNameForExecutable(exe string) string { identity := filepath.Clean(exe) if runtime.GOOS == "windows" { identity = strings.ToLower(identity) } sum := sha256.Sum256([]byte(identity)) userScope := currentUserScope() return `\\.\pipe\reims-go-control-` + hex.EncodeToString(sum[:8]) + "-" + userScope }